Conditional Where If Results

Nov 6, 2007

This is my query:


SELECT Class.ClassID, Class.Comments, Class.Address1, City.City, Class.State, Instructor.FirstName, Instructor.LastName, ClassInstructor.IsPrimary

FROM Class

LEFT OUTER JOIN City ON City.CityID = Class.CityID

LEFT OUTER JOIN ClassInstructor ON ClassInstructor.ClassID = Class.ClassID

LEFT OUTER JOIN Instructor ON Instructor.InstructorID = ClassInstructor.InstructorID

WHERE Class.ClassID = @ClassID

AND ClassInstructor.IsPrimary=1



The problem is that if the class doesn't have an instructor yet, the query doesn't return results because even though I am using a LEFT JOIN on the class table, the "ClassInstructor.IsPrimary=1" statement will cause no results. I want results from the other class fields even if the class doesn't have an instructor.

I tried this and it works but seems kinda inefficient:


SELECT @cnt=COUNT(*)FROM ClassInstructor

WHERE ClassID = @ClassID

AND ClassInstructor.IsPrimary=1


IF @cnt>0

BEGIN

SELECT Class.ClassID, Class.Comments, Class.Address1, City.City, Class.State, Instructor.FirstName, Instructor.LastName, ClassInstructor.IsPrimary

FROM Class

LEFT OUTER JOIN City ON City.CityID = Class.CityID

LEFT OUTER JOIN ClassInstructor ON ClassInstructor.ClassID = Class.ClassID

LEFT OUTER JOIN Instructor ON Instructor.InstructorID = ClassInstructor.InstructorID

WHERE Class.ClassID = @ClassID

AND ClassInstructor.IsPrimary=1

END



Is there a better way to do this?

View 3 Replies


ADVERTISEMENT

Conditional Query Results

Dec 19, 2006

Hello everybody,After several attempts of writing the query, I had to post myrequirement in the forum.Here is what I have, what I need and what I did.Table ACol1 Col21 Nm12 Nm23 Nm3Table BCol1 Col210 10020 200Table CCol1 (A.Col1) Col2 (B.Col1)1 102 10Table DCol1 (A.Col1) Col21 Value12 Value2I need results based on below criteria,1.Criteria - B.Col2 = 100ResultsetA.Col1 D.Col11 Value12 Value22.Criteria - B.Col2 =""A.Col1 D.Col11 Value12 Value23 NULL3.Criteria - B.Col2 =200Empty resultsetHere is the query I tried, but looks its not working. Probably there isa better way to do this.DDL and DML statements:create table #tab1 (a1 int, a2 nvarchar(20))create table #tab2 (b1 int, b2 int)create table #tab3 (c1 int, c2 int)create table #tab4 (d1 int, d2 nvarchar(20))insert into #tab1 values (1, 'nm1')insert into #tab1 values (2, 'nm2')insert into #tab1 values (3, 'nm3')insert into #tab2 values (10, 100)insert into #tab2 values (20, 200)insert into #tab3 values (1, 10)insert into #tab3 values (2, 10)insert into #tab4 values (1, 'value1')insert into #tab4 values (2, 'value2')selecta.a1, d.d2from #tab1 aleft join #tab3 bon a.a1 = b.c1left join #tab2 con b.c2 = c.b1left join #tab4 don a.a1 = d.d1wherec.b2 = [100 or 200 or ''] or exists (select 1 from #tab4 dwhere a.a1 = d.d1and c.b2 = [100 or 200 or ''] )The above query works well to give results for Criteria 1 and Criteria3, but doesn't return for '' (criteria 2). I couldn't manage crackingthe solution. I shall try once again, but meanwhile if anyone couldhelp me in this, that would be great.Thanks.

View 3 Replies View Related

Transact SQL :: How To Get Results Based On Conditional Where Clause

Jul 14, 2015

My source table has two columns... Policynum and PolicyStartdate and data looks like..
.
Policynum              PolicyStartdate
123G                       01/01/2012    
456D                       02/16/2012     
789A                       01/21/2012
163J                       05/25/2012

Now my output should return based on 3 parameters..

First two parameters are date range... let say @fromdt and @todt

Third parameter is @policynum

Scenario-1: Enter dates in date range param and leave policynum param blank
Ex: policystartdate between '01/01/2012 and '01/31/2012'.... It returns 1st and 3rd rows from above in the output

Scenario-2: enter policy num in policynum param and don't select any dates
Ex:  policynum ='456D'     It returns 2nd row in the output

Scenario-3: Select dates in date range param and enter policynum in param
Ex: policystartdate between '01/01/2012 and '01/31/2012' and policynum
='163J'.  it should return only 4th row even though dates were selected(Override date range when policynum is entered in param and just return specified policynum row in the output)

I need t-sql code to get above results.

View 12 Replies View Related

Conditional Subscription / Conditional Execution Of Report

Mar 7, 2008



Hello everyone,

Is there a way in order to execute a subscribed report based on a certain criteria?

For example, let's say send a report to users when data exist on the report else if no data is returned by the query
executed by the report then it will not send the report to users.

My current situation here is that users tend to say that this should not happen, since no pertinent information is contained in the report, why would they receive email with blank data in it.


Any help or suggestions will be much appreciated.

Thanks,
Larry

View 6 Replies View Related

Conditional Formatting - Not So Conditional??

Dec 15, 2006

I have the following code in the color property of a textbox. However, when I run my report all of the values in this column display in green regardless of their value.

=SWITCH(Fields!Wrap.Value >= 3, "Red", Fields!Wrap.Value < 3, "Green")

I already tried =iif(Fields!Wrap.Value >= 3 , "Red", "Green") and got the same results.

Is it because this is a matrix report? What am I doing wrong?

Thanks in advance . . .

View 4 Replies View Related

Is There A Way To Hold The Results Of A Select Query Then Operate On The Results And Changes Will Be Reflected On The Actual Data?

Apr 1, 2007

hi,  like, if i need to do delete some items with the id = 10000 then also need to update on the remaining items on the with the same idthen i will need to go through all the records to fetch the items with the same id right?  so, is there something that i can use to hold those records so that i can do the delete and update just on those records  and don't need to query twice? or is there a way to do that in one go ?thanks in advance! 

View 1 Replies View Related

SQL Server 2008 :: Elegant Way For Returning All Results When Subquery Returns No Results?

Mar 25, 2015

I have four tables: Customer (CustomerId INT, CountyId INT), County (CountyId INT), Search(SearchId INT), and SearchCriteria (SearchCriteriaId INT, SearchId INT, CountyId INT, [others not related to this]).

I want to search Customer based off of the Search record, which could have multiple SearchCriteria records. However, if there aren't any SearchCriteria records with CountyId populated for a given Search, I want it to assume to get all Customer records, regardless of CountyId.

Right now, I'm doing it this way.

DECLARE @SearchId INT = 100
SELECT * FROM Customer WHERE
CountyId IN
(
SELECT CASE WHEN EXISTS(SELECT CountyId FROM SearchCriteria WHERE SearchId = @SearchId)
THEN SearchCriteria.CountyId

[Code] .....

This works; it just seems cludgy. Is there a more elegant way to do this?

View 4 Replies View Related

Need To Display Results Of A Query, Then Use A Drop Down List To Filter The Results.

Feb 12, 2008

Hello. I currently have a website that has a table on one webpage. When a record is clicked, the primary key of that record is transfered in the query string to another page and fed into an sql statement. In this case its selecting a project on the first page, and displaying all the scripts for that project on another page. I also have an additional dropdownlist on the second page that i use to filter the scripts by an attribute called 'testdomain'. At present this works to an extent. When i click a project, i am navigated to the scripts page which is empty except for the dropdownlist. i then select a 'testdomain' from the dropdownlist and the page populates with scripts (formview) for the particular test domain. what i would like is for all the scripts to be displayed using the formview in the first instance when the user arrives at the second page. from there, they can then filter the scripts using the dropdownlist.
My current SQL statement is as follows.
SelectCommand="SELECT * FROM [TestScript] WHERE (([ProjectID] = @ProjectID) AND ([TestDomain] = @TestDomain))"
So what is happening is when testdomain = a null value, it does not select any scripts. Is there a way i can achieve the behaivour of the page as i outlined above? Any help would be appreciated.
Thanks,
James.

View 1 Replies View Related

Stored Proc Results Are Displaying In The Messages Tab Instead Of Results Tab- URGENT

May 14, 2008




Hi All,
I have a stored proc which is executing successfully...but the results of that stored proc are displaying in the Messages Tab instaed of results Tab. And in the Results Tab the results shows as 0..So, Any clue friends..it is very urgent..I am trying to call this stored proc in my Report in SSRS as well but the stored proc is not displaying there also...Please help me ASAP..

Thanks
dotnetdev1

View 4 Replies View Related

Mind-boggling Gridview Results! Different Results For Different Teams..

Jun 18, 2008

Hi all, I have the following SQLDataSource statement which connects to my Gridview:<asp:SqlDataSource ID="SqlDataSourceStandings" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"  SelectCommand="SELECT P.firstName, P.lastName, T.teamName, IsNull(P.gamesPlayed, 0) as gamesPlayed, IsNull(P.plateAppearances,0) as plateAppearances, IsNull( (P.plateAppearances - (P.sacrifices + P.walks)) ,0) as atbats, IsNull(P.hits,0) as hits, P.hits/(CONVERT(Decimal(5,2), IsNull(NullIF(P.atbats, 0), 1))) AS [average], (P.hits + P.walks)/(CONVERT(Decimal(5,2), IsNull(NullIF( (P.atbats + P.sacrifices + P.walks) , 0), 1)))  AS [OBP], (P.hits - (P.doubles + P.triples + P.homeRuns) + (2 * P.doubles) + (3 * P.triples) + (4 * P.homeRuns)) / (CONVERT(Decimal(5,2), IsNull(NullIF(P.atbats, 0), 1))) AS [SLG], P.singles, P.doubles, P.triples, P.homeRuns, P.walks, P.sacrifices, P.runs, P.rbis FROM Players P INNER JOIN Teams T ON P.team = T.teamID ORDER BY P.firstName, P.lastName"></asp:SqlDataSource>There are 8 teams in the database, and somehow the average and obp results are as expected for all teams except where T.teamID = 1.  This doesn't make sense to me at all!  For example, I get the following results with this same query: First NameLast NameTeamGPPAABHAVGOBPSLG1B2B3BHRBBSACRRBI

BrianAustinHope83432230.7187500.7352941.15625014612201221

GabrielHelbigSafe Haven62119141.0000000.9375002.1428576404111519

MarkusJavorSafe Haven82927200.8695650.8000001.21739114501021218

RobBennettMelville83029240.8275860.8333331.55172411904102117

AdamBiesenthalSafe Haven82929210.9130430.9130431.56521712631001015

ErikGalvezMelville82625180.7200000.7307691.24000011322101015 As you can see, all teams except for Safe Haven's have the correct AVG and OBP.  Since AVG is simply H/AB, it doesn't make sense for Gabriel Helbig's results to be 1.00000. Can anyone shed ANY light on this please?Thank you in advance,Markuu  ***As a side note, could anyone also let me know how I could format the output so that AVG and OBP are only 3 decimal places? (ex: 0.719 for the 1st result)*** 

View 2 Replies View Related

Removing Individual Results From A Paged Set Of Results.

Oct 19, 2007

Hi,
I have a web form that lets users search for people in my database they wish to contact. The database returns a paged set of results using a CTE, Top X, and Row_number().
I would like to give my users to option of removing individual people from this list but cannot find a way to do this.
I have tried creating a session variable with a comma delimited list of ID's that I pass to my sproc and use in a NOT IN() statement. But I keep getting a "Input string was not in a correct format." Error Message.
Is there any way to do this? I am still new to stored procedures so any advice would be helpful.
Thanks
 

View 3 Replies View Related

PASTE SQL RESULTS INTO EXCEL - Funny Results

Jan 30, 2008

Hi, when I copy and paste results from query analyzer into Excel it appears that values with zeroes at the end loose the zeroes. Example, if I copy and paste V128.0 into an Excel cell it comes out as V128 or if I copy 178.70 it displays as 178.7 - any ideas? I'm using SQL Enterprise Manager for 2000.

View 6 Replies View Related

Conditional FROM/WHERE

Apr 13, 2001

SQL 7

Hi All !!

I want to know how I can create conditional FROM WHERE clauses like below ..

SELECT X,X,X
FROM
CASE @intAltSQL > 0 Then Blah Blah Blah END
CASE @intAltSQL = 0 Then Blah END
WHERE
CASE @intAltSQL > 0 Then Blah Blah Blah END
CASE @intAltSQL = 0 Then Blah END

Thoughts ?

Thanks

View 4 Replies View Related

Conditional When

Jun 23, 2008

Is anything similar to this possible without writing whole query in every begin block or without dynamic sql:

proc(@arg1 bit)

select * from table where x=y
if @arg1 = 1 begin
and when a=b
end
order by date

View 6 Replies View Related

Conditional -- ?

Jul 23, 2005

What does "conditional" mean as a command? sp_who2 reports this forsome sessions, along with "insert" etc.Thanks,Jim Geissman

View 2 Replies View Related

Conditional Sum?

Apr 23, 2007

Hi,



Is it possible to have a conditional sum based on an item type existance in a set of values?



Example if i have the following set:

A

A

A

A

B



I just wanna sum B else if B doens't exist sum A





Best Regards,

Luis Simoes

View 7 Replies View Related

Conditional Inner Join?

Jan 30, 2007

Im faced with the following design issue..
on my site there are different profiles: a city profile, a restaurant profile and a user profile.
in my DB:City profiles are stored in tbCities cityID int PK shortname nvarchar(50) forumID int FK (...)
Restaurant profiles are stored in tbRests restID int PK shortname nvarchar(50) forumID int FK (...)
User profiles are stored in tbUsers userID int PK shortname nvarchar(50) forumID int FK (...)
as you can see a single ID value (for CityID,restID or userid) might occur in multiple tables (e.g. ID 12 may exist in tbRests and in tbUsers)Each of these profile owners can start a forum on their profile.
forumID in each of the above tables is a FK to the PK in tbForums:forumID  intforumname nvarchar(50) (...)
Now imagine the following:
a site visitor searches ALL forums...say he finds the following forums:ForumID Forumname1 you opinion on politics2 is there life in space?3 who should be the next president of the USA?
a user may want to click on the forum name to go to the profile the forum belongs to.And then there's a problem, because I dont know in which table I should look for the forum ID...OR I would have to scan all tables (tbCities,tbRests and tbUsers) for that specific forumid,which is time-consuming and I dont want that!
so if a user would click on forumID 2 (is there life in space?)
I want to do a conditional inner join for the tablecontainingforumID (which may be tbCities,tbRests or tbUsers)
select tablecontainingforumID.shortname FROM tablecontainingforumID tINNER JOIN tbForums f ON t.ForumID=f.ForumIDwhere f.ForumID=2
I hope my problem is clear..any suggestions are welcome (im even willing to change my DB design if that would increase effectivity)
 

View 6 Replies View Related

If Conditional Problem In T-Sql

Jan 31, 2007

I encounter a T-Sql problem related to if conditional processing:The following script execute an insert statement depending on whether column 'ReportTitle' exists in table ReportPreferences. However it gets executed even when ReportTitle column is not present.Could anyone offer some advice?  IF(Coalesce(Col_length('ReportPreferences','ReportTitle'),0) > 0) BeginINSERT INTO dbo.DefaultsSELECT FinancialPlannerID,ReportTitleFROM dbo.ReportPreferencesendGO 

View 6 Replies View Related

Conditional Where Statement

Jul 23, 2007

I have a stored procedure that performs a search function with params:@username nvarchar(50)@country nvarchar(50)and like 10 more.A user may provide values for these params optionally.So when the @username var is left blank, there should be no filtering on the username field (every field should be selected regardless of the username)Currently my statement is:select username,country from myUsers whereusername=@username and country=@countryWith this statement when a user provides no value for username the username field selects on ''m which returns ofcourse nothing...What can I do to solve this?Thanks!

View 6 Replies View Related

SQL Conditional WHERE Statement

Feb 4, 2008

Hi, is it possible to do a conditional WHERE in T-SQL? I have a table with a column that consists of a reference that starts with either a single alpha character or two alpha characters followed by four numeric digits (the numeric portion is always unique but the alpha isn’t). E.g. A1234, AB1235, AB1236, C1237, HT1238. What I want to do is select a range of rows based on the numeric portion of this reference column. In other words I want to select say 50 rows starting from row 1000 (rows 1000 to 1050) regardless of whether there is one or two alpha characters preceding the numerics.The Stored procedure I have so far works (using COUNT for testing) for selecting a range of rows that has two alpha's at the start. However, if I simply add an OR to the WHERE to select rows where there is a single alpha in the reference column, when a single alpha reference is found it will fail the first logical check for two alpha's giving an error condition. Therefore, how can I incorporate a conditional WHERE using IF or some alternative method, so that it will also give me all the rows in the number sequence that start with either single or double alpha's within the same SELECT / WHERE statement?

Thanks for any help.ALTER PROCEDURE [dbo].[sp_Test]

(
@startRef int,
@endRef int
)

AS

BEGIN

SELECT Count(*) FROM myTable
WHERE ((SUBSTRING(Ref,3,LEN(Ref)-2) BETWEEN @startRef AND (@startRef + @endRef)))

END
RETURN
 

View 2 Replies View Related

Conditional SQL Question

Feb 23, 2008

I have an SqlDataSource that uses a value from the query string in the WHERE clause of the sql statement.
The sql is something like this:
SELECT * FROM myTable WHERE myfield = @myfield
and I have the QueryStringParameter setup like this:
<asp:QueryStringParameter Name="myfield" QueryStringField="myfield" />
What I need is for the sql statement to return all records in the case that "myfield" is not defined in the query string.
How would I implement this?
Thanks,
Joshua Foulk

View 6 Replies View Related

Conditional Update

Feb 21, 2006

Hello all, my update statement works as expected, but lacks some conditional logic. How can I change the statement to not decrement qtyonhand if the quantity is 0? Additionally, I would need to return to the calling application something that would allow me to populate a label with a message to the user.. How can that be accomplished?
Here is my sproc:CREATE PROCEDURE [webuser].[cssp_removeItem]
@lblID int
AS
Update cstb_inventoryset qtyonhand = qtyonhand -1where Id = @lblIDGO
Here is my app code:
Try
Dim cmd As SqlCommand = cn.CreateCommand
cmd = New SqlCommand("cssp_removeItem", cn)
cmd.CommandType = CommandType.StoredProcedure
With cmd
cmd.Parameters.Add("@lblId", SqlDbType.Int).Value = lblId.Text
End With
If Not cn.State = ConnectionState.Open Then
cn.Open()
End If
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.ToString)
Finally
If Not cn.State = ConnectionState.Closed Then
cn.Close()
cn = Nothing
End If
 

View 6 Replies View Related

Conditional WHERE Clause

May 8, 2006

Hi,
[SQL 2005 Express]
I would like a DropDownList to be populated differently depending on the selected value in a FormView.
If the FormView's selected value (CompanyID) is 2, then the DropDownList should show all Advisers from the relevant Company.  Otherwise, the DropDownList should show all Advisers from the relevant Company where the TypeID field is 3.
Here is the SQL for case 1:
SELECT    AdviserID,    AdviserName FROM    Advisers WHERE    (CompanyID = @CompanyID).
Here's the SQL for case 2:
SELECT    AdviserID,    AdviserName FROM   Advisers WHERE    (CompanyID = @CompanyID) AND    (TypeID = 3).
Here's my best (failed) attempt to get what I want:
SELECT    AdviserID,    AdviserName FROM   Advisers WHERE    IF @CompanyID = 2 THEN      BEGIN         (CompanyID = @CompanyID)      END   ELSE      BEGIN         (CompanyID = @CompanyID) AND          (TypeID = 3)      END
I've also tried:
SELECT    AdviserID,    AdviserName FROM   Advisers WHERE    CASE @CompanyID       WHEN 2 THEN (CompanyID = @CompanyID)      ELSE (CompanyID = @CompanyID) AND          (TypeID = 3)   END
and 
SELECT    AdviserID,    AdviserName FROM   Advisers WHERE    CASE WHEN (@CompanyID = 2) THEN (CompanyID = @CompanyID)      ELSE (CompanyID = @CompanyID) AND (TypeID = 3)   END
I'd be very grateul to know (a) what the correct syntax for this is and (b) if it can be achieved using a parametised query, rather than a stored procedure.
Thanks very much.
Regards
Gary

View 7 Replies View Related

Conditional Foreign Key - Can It Be Done???

May 17, 2001

Hello Folks,

Well I've hit the wall on this one:

I'm wondering if one can designate a conditional foreign key that relates to one of many different tables depending on the "type" column in the foreign key's. My goal is to come up with some SQL code that will allow for this in a Create table statement. (By the way I'm using MS SQL-7 but I'm wondering if this can be done in general.)

I have two simple cases below that show illustrate what I'm trying to do:
Thanks in advance, -JerryZZ


---------------------------------------------------------
Case 1: The foreign key relation is to a primary key

Table: Invoices
-Fields:
---InvoiceID ..... (primary key)
---BilleeID ...... (fkey to Manfacturers.ManfID IF BilleeType=M)
...................(fkey to Distibutors.DistID IF BilleeType=D)
---BilleeType .....(constraint = M or D)

Table: Manufacturers
-Fields:
---ManfID ........ (primary key)
---CompanyName.. (not null)

Table: Distributors
-Fields:
---DistID ........ (primary key)
---CompanyName .. (not null)



---------------------------------------------------------
Case 2: The foreign key relation is to a unique "not null" non-primary key

Table: InvoicesEmail
-Fields:
---InvoiceID ..... (primary key)
---EmailAddress .. (fkey to Manfacturers.EmailAddress IF BilleeType=M)
...................(fkey to Distibutors.EmailAddress IF BilleeType=D)
---BilleeType .....(constraint = M or D)

Table: Manufacturers
-Fields:
---ManfID ........ (primary key)
---EmailAddress .. (unique, not null)

Table: Distributors
-Fields:
---DistID ........ (primary key)
---EmailAddress .. (unique, not null)

---------------End-O-Message-------------------------------------

View 2 Replies View Related

Conditional Delete

Nov 15, 2000

Hi, ladies and gentelmen!
Can you help me with following trouble:
I got a table (let it be called SomeTable) in which there's one nullable field (let's call it SomeField) among many others. PRIMARY KEY for SomeTable is of INT IDENTITY type.
Business rules are following: only records that have SomeField IS NULL can be deleted, so I need to perform conditional delete (for cases like DELETE SomeTable). I don't like idea about using SP here, so I tried to solve the task by means of trigger. However, when DELETE clause is used within a transaction and there're records affected by the trigger that don't match business rule, trigger uses ROLLBACK TRAN and then deletes only matching rows from target table. Everything works fine with our SomeTable, but not so fine with the transaction, because due to ROLLBACK TRAN statement in trigger body this transaction is rolled back (as it is described in documentation). But I don't wanna ALL my transaction rolled back! So, is there in SQL Server 7.0 any way to rollback only changes that caused trigger to fire? Something like ROLLBACK TRIGGER?

View 1 Replies View Related

Help With IF THEN - Conditional ORDER BY

Dec 2, 1999

I would like to write the following (pseudo) stored procedure, but am having problem with the syntax:

Create Procedure spSort
@IDContract nvarchar(10)
@SortOrder int

SELECT * FROM Contracts
WHERE IDContract = @IDContract
IF @SortOrder = 0
BEGIN
ORDER BY ContractDate
END
IF @SortOrder = 1 THEN
BEGIN
ORDER BY ShippingPeriod
END

The problem is in conditionally setting the sort order. The actual sp is quite complex and I don't really want to have to use two procedures (one for ordering by ShippingPeriod and one for ordering by ContractDate

Any suggestions please?

Many thanks
Jeremy Holt

View 2 Replies View Related

Conditional Insert

Oct 29, 2006

Hi,

Originally had 2 tables, fullsource and ssotarget. I did the following extract on fullsource due to its irregular schema and inserted into ssotarget:

INSERT SSOTARGET (pin, address1, address2, address3, MemberNo, Tel1, Tel2, Tel3, Tel4, DOB, Email, IDNumber, Title, Initials, Firstname, Surname, STATUS)

SELECT
PIN,
MAX(CASE WHEN HEADER = 'ADDRESS DETAILS' AND PROPERTY = 'LINE 1' THEN VALUE ELSE NULL END) AS address1,
MAX(CASE WHEN HEADER = 'ADDRESS DETAILS' AND PROPERTY = 'LINE 2' THEN VALUE ELSE NULL END) AS address2,
MAX(CASE WHEN HEADER = 'ADDRESS DETAILS' AND PROPERTY = 'LINE 3' THEN VALUE ELSE NULL END) AS address3,
MAX(CASE WHEN HEADER = 'ACOMPANY' AND PROPERTY = 'Membership Number' THEN VALUE ELSE NULL END) AS MemberNo,
MAX(CASE WHEN HEADER = 'CONTACT DETAILS' AND PROPERTY = 'Preferred method of contact*' THEN VALUE ELSE NULL END) AS Tel1,
MAX(CASE WHEN HEADER = 'CONTACT DETAILS' AND PROPERTY = 'Tel number (o/h) e.g. 011 2690000' THEN VALUE ELSE NULL END) AS Tel2,
MAX(CASE WHEN HEADER = 'CONTACT DETAILS' AND PROPERTY = 'Mobile number e.g. 0821234567' THEN VALUE ELSE NULL END) AS Tel3,
MAX(CASE WHEN HEADER = 'CONTACT DETAILS' AND PROPERTY = 'Fax number e.g. 011 2691000' THEN VALUE ELSE NULL END) AS Tel4,
MAX(CASE WHEN HEADER = 'Date Of Birth' AND PROPERTY = 'eg. 04 Jan 1965' THEN VALUE ELSE NULL END) AS DOB,
MAX(CASE WHEN HEADER = 'Email address' AND PROPERTY = 'Email Address' THEN VALUE ELSE NULL END) AS Email,
MAX(CASE WHEN HEADER = 'ID Number' AND PROPERTY = 'ID Number' THEN VALUE ELSE NULL END) AS IDNumber,
MAX(CASE WHEN HEADER = 'Member Information' AND PROPERTY = 'Title' THEN VALUE ELSE NULL END) AS Title,
MAX(CASE WHEN HEADER = 'Member Information' AND PROPERTY = 'Initials' THEN VALUE ELSE NULL END) AS Initials,
MAX(CASE WHEN HEADER = 'Member Information' AND PROPERTY = 'Firstname' THEN VALUE ELSE NULL END) AS Firstname,
MAX(CASE WHEN HEADER = 'Member Information' AND PROPERTY = 'Surname' THEN VALUE ELSE NULL END) AS Surname,
MAX(CASE WHEN HEADER = 'ACOMPANY' AND PROPERTY = 'Membership Number' THEN STATUS ELSE NULL END) AS STATUS

FROM

FULLSOURCE

GROUP BY PIN


Now how can I reverse this to insert all the values back to tbl FULLSOURCE from maybe an updated SSOTARGET Tbl. FULLSOURCE looks like this:

SELECT [PIN]
,[SYSTEM]
,[Header]
,[Property]
,[Value]
,[Status]
,[ID_Header]
,[ID_Property]
FROM [fullsource]

View 1 Replies View Related

Conditional Select

Nov 8, 2007

I am trying to write query that will select calls that only show up when the resolution returned from the case in the sub query is 'y'. When I do the group by some calls will show up twice because of a null and a 'y' resolution return. I want to only select a call if there is a 'y' that shows for all resolutions associated with that call. If there are any null resolutions for the call I don't want it to show up in my returned values. This is what I have so far, but I can't figure out how to make it drop both instances of the callID if one instance is null.


Code:

SELECT C.CallID, P.PrimarySupportGroupID, P.PrimaryTeamName, T1.Resolution, CASE C.CallID WHEN T1.Resolution IS NOT NULL THEN 'Y' ELSE 'N' END
FROM HEAT.dbo.CallLog C,
(SELECT CallID, CASE WHEN A1.Resolution = '' THEN 'Y' ELSE NULL END AS Resolution
FROM HEAT.dbo.Asgnmnt A1) T1, HEAT.dbo.Profile P
WHERE C.CallID = T1.CallID AND C.CustID = P.CustID AND (P.PrimarySupportGroupID = 'ATS') AND (P.PrimaryTeamName = 'Beta')
GROUP BY C.CallID, P.PrimarySupportGroupID, P.PrimaryTeamName, T1.Resolution



If anyone could help me out with this or at least give me a little information and point me in the right direction I would really appreciate it.

Thank you
Court

View 1 Replies View Related

Conditional SQL Count

Feb 13, 2006

Is there a way to have a conditonal count within a stored procedure

ie


Code:

Select field, field2, Count(if Field3 > 0)



(i know this code will not work)

The idea is to only count records if they have a value greater than zero

View 7 Replies View Related

Conditional Trigger

Jul 17, 2006

I have a trigger that updates values in a table when col2 is updated by a stored procedure.

I'd like to make this a conditonal trigger to prevent negative values from being inserted in the table. I'm not familiar with the syntax of triggers enough to get this to work and I've search for a reference with no luck.

Here's the current trigger code:


Code:

FOR INSERT, UPDATE
AS
UPDATE table1
SET col4= col1 - col2 - col3



I need to evaulate (col1 - col2 - col3) to see if it's less than zero. If it is, I want to set col4=0.

This is what I've tried, but it doesn't work. Any help is appreciated:


Code:

FOR INSERT, UPDATE
AS
select col1, col2, col3 from table1
if (col1 - col2 - col3) < 0
UPDATE table1
SET col4 = 0
else
UPDATE table1
SET col4= col1 - col2 - col3

View 3 Replies View Related

Conditional Insert

Oct 22, 2004

I need to do a conditional insert. This is what I have tried, it does not work.
What am I doing incorrectly?

IF (SELECT COUNT(*) FROM TBL1 INNER JOIN
TBL2 ON TBL1.MODEL_ID = TBL2.MODEL_ID INNER JOIN
TBL3 ON TBL1.PRO_TYPE = TBL3.TYPE INNER JOIN
TBL4 ON TBL1.PRO_SITE = TBL4.WHDESC) > 0

INSERT INTO TBL5
SELECT TBL1.PRO_SITE, TBL1.MODEL_ID,
TBL1.NUM_SLOTS, TBL1.TARGET_DAYS, GETDATE() AS Expr1,
TBL3.TYPE_ID, NULL AS Expr2, TBL1.NUM_SLOTS AS Expr3, NULL AS Expr4, NULL
AS Expr5, 0 AS RAMP
FROM TBL1 INNER JOIN
TBL2 ON TBL1.MODEL_ID = TBL2.MODEL_ID INNER JOIN
TBL3 ON TBL1.PRO_TYPE = TBL3.TYPE INNER JOIN
TBL4 ON TBL1.PRO_SITE = TBL4.WHDESC

UPDATE TBL5
SET TEAMS=0
GO
UPDATE TBL5
SET TEAMS = (SELECT NUM_SLOTS
FROM TBL6 R1
WHERE (R1.TEAM_ID = TBL5.TEAM_ID)
)
WHERE (TEAM_ID =
(SELECT TEAM_ID
FROM TBL6 R3
WHERE (R3.TEAM_ID = TBL5.TEAM_ID)))
GO
UPDATE TBL5
SET TOTALTEAMS = TEAMS + RAMP
GO

I need to do a conditional because sometimes the select that returns data contains no records.

Thanks...

View 1 Replies View Related

Conditional SQL Triggers

Oct 29, 2004

Hi, I've been handed a task at work where I need to use SQL triggers to solve the problem.

I need to be able to run a Trigger when, and only when, a cell in a specific column in a row changes to a specific value.

For instance, say I have the following table:
CREATE TABLE source
(
ID tinyint NOT NULL,
contacttype tinyint NOT NULL,
)

If one of the rows is UPDATE'd to contacttype = 2, I want to fire a trigger, but not if it changes to anything else.

How can this be performed?

View 8 Replies View Related

Conditional Execution Of The Next Job In DTS

Jan 3, 2005

I have a job which exports and emails the data from a table (subject to some conditions) . The data is exported to a test file. I donot want to send the email if there are no rows exported. or the filesieze is 0. Otherwsie I want to send the email with this text file as attachement.

Any ideas?

Thanks
Ragu

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved