Complex SQL CASE WHEN - sql

I am trying to do a SELECT using a CASE statement, and I 'm getting errors that do not make sense. My statement appears to adhere to any SQL syntax rules but I'm getting the good ol' "the multi part identifier to_do.[item_id] AND to_do.[item] cannot be bound.
This does not make sense because the column names are correct with respect to the table columns.
Here is the SQL:
SELECT to_do.[item_id],
to_do.[item] = CASE to_do.encounter_id WHEN 0 THEN CONVERT(NVARCHAR, e.[date], 101 ) + ' - ' + p.[first_name] + ' ' + p.[last_name] + ' - ' + to_do.[item] AS to_do.[item] ELSE to_do.[item] END,
to_do.[complete],
to_do.[encounter_id],
e.[date],
p.[last_name] + ', ' + p.[first_name] AS [p_name]
FROM [dbo].[to_do] LEFT OUTER JOIN
[dbo].[encounter] e ON
to_do.[encounter_id] = e.[encounter_id] LEFT OUTER JOIN
[dbo].[patients] p ON
e.[mrn] = p.[mrn]
WHERE to_do.[user_id] = #user_id
Any ideas what I'm doing wrong here ? Based off previous experience I should be able to use CASE like this but maybe I've just been staring at it too long and don't see the obvious.
Thanks!

You can't use a table prefix in a column alias to_do.[item] = CASE ... is presumably intended to be [item] = CASE ...
(Also you have a rogue AS in the middle of the CASE itself that needs removing)

The AS {alias} needs to go after the END. I'd rewrite as follows:
SELECT to_do.[item_id],
CASE to_do.encounter_id WHEN 0 THEN CONVERT(NVARCHAR, e.[date], 101 ) + ' - ' + p.[first_name] + ' ' + p.[last_name] + ' - ' + to_do.[item] ELSE to_do.[item] END AS [item] ,
...

Your AS is in the wrong place-- try
to_do.[item] = CASE to_do.encounter_id WHEN 0 THEN CONVERT(NVARCHAR, e.[date], 101 ) + ' - ' + p.[first_name] + ' ' + p.[last_name] + ' - ' + to_do.[item] ELSE to_do.[item] END AS to_do.[item] ,

Related

I'm having an issue with syntax in a Stored SQL Procedure

I'm trying to add three additional columns to a stored procedure (I don't have a lot of experience in stored procedures), the columns are Family ID, Address, and Phone No. Although I've run the query and confirmed the syntax for my select statement is correct, when I add the statement to the stored proc, I receive the following error: Incorrect syntax near 'capPrograms'(this would be line 14). I know this probably has to do with hoe I'm trying to implement my statement in the procedure to update it, but I'm not quite sure what the issues as I've tried several changes with similar or more extensive errors. Any assistance is appreciated, I've included the block of code I'm working with below:
SELECT capCase.Id AS capCase_Id,
capCase.DateApplied AS capCase_DateApplied,
CASE
WHEN ISNUMERIC(#cases.origCaseYear)=1 THEN CAST(origCaseYear + 2004 AS VARCHAR) + ' - ' + CAST(capCase.IdYear + 2004 AS VARCHAR)
WHEN #cases.maxRolloverYear IS NOT NULL THEN CAST(capCase.IdYear + 2004 AS VARCHAR) + ' - ' + CAST(#cases.MaxRolloverYear + 2004 AS VARCHAR)
ELSE CAST(capCase.IdYear + 2004 AS VARCHAR)
END AS capCase_IdYear,
Person.id as Person_id,
Person.LastName + ', ' + Person.FirstName AS PersonPrint_Name,
person.idFamily AS Family_ID, person.homePhone AS Phone_No, (SELECT family.physicalAddress1+ ', ' + family. physicalAddressCity+ ' ' +family. physicalAddressZip) AS Address
FROM Family
LEFT JOIN person ON family.Id = person.idFamily;
capPrograms.Program AS capPrograms_Program,
capStatus.Status AS capStatus_Status,
#lastFollowup.followupDate AS capCaseFollowup_Date,
CASE
WHEN capCase.IdCaseWorker IS NULL THEN 'No Worker Assigned'
ELSE caseWorker.LastName + ', ' + caseWorker.FirstName + ISNULL('<' + caseWorker.EmailWork + '>', '')
END AS capCase_IdCaseWorker,
capcaseDenialReason.reason AS capCase_idDenialReason,
Too long to comment, so I added a bunch of comments in your code. You have, A LOT of issues.
SELECT
capCase.Id AS capCase_Id,
capCase.DateApplied AS capCase_DateApplied,
CASE
--here you are referencing a temp table, which isn't joined below
WHEN ISNUMERIC(#cases.origCaseYear)=1 THEN CAST(origCaseYear + 2004 AS VARCHAR) + ' - ' + CAST(capCase.IdYear + 2004 AS VARCHAR)
WHEN #cases.maxRolloverYear IS NOT NULL THEN CAST(capCase.IdYear + 2004 AS VARCHAR) + ' - ' + CAST(#cases.MaxRolloverYear + 2004 AS VARCHAR)
ELSE CAST(capCase.IdYear + 2004 AS VARCHAR)
END AS capCase_IdYear,
Person.id as Person_id,
Person.LastName + ', ' + Person.FirstName AS PersonPrint_Name,
person.idFamily AS Family_ID,
person.homePhone AS Phone_No,
--this subquery as no from clause... that's an issue... you probably want to remove it completly and replace it with the one below
(SELECT family.physicalAddress1+ ', ' + family. physicalAddressCity+ ' ' +family. physicalAddressZip) AS Address,
--this is likely what you want
family.physicalAddress1 + ', ' + family. physicalAddressCity + ' ' + family. physicalAddressZip AS AddressCorrected
FROM Family
LEFT JOIN person ON
family.Id = person.idFamily; --you have a ; here, which terminates the statement. Everything else below isn't included
--Here you need to join the capPrograms and #lastFollowup table..
--here, you listed some columns, without a table reference. You need to join the table above, and move these columns above the FROM clause
capPrograms.Program AS capPrograms_Program,
capStatus.Status AS capStatus_Status,
#lastFollowup.followupDate AS capCaseFollowup_Date,
CASE
WHEN capCase.IdCaseWorker IS NULL THEN 'No Worker Assigned'
ELSE caseWorker.LastName + ', ' + caseWorker.FirstName + ISNULL('<' + caseWorker.EmailWork + '>', '')
END AS capCase_IdCaseWorker,
capcaseDenialReason.reason AS capCase_idDenialReason,

some weird signs appearing on SQL SERVER Query output

i have written a SELECT Query on SQL SERVER 2014 . I have got the desired output . but an apostrophe symbol(') appearing on 'TaskAction' field data(at the end of each data). here it is my script:
SELECT
WOtask.PK,
WOPK,
TaskNo,
TaskAction =
CASE
WHEN WOTask.AssetPK IS NOT NULL THEN '<b>' + Asset.AssetName + ' [' + Asset.AssetID + ']</b> ' + CASE
WHEN Asset.Vicinity IS NOT NULL AND
Asset.Vicinity <> '''' THEN RTRIM(Asset.Vicinity) + ': '
ELSE ''''
END + WOtask.TaskAction + CASE
WHEN CONVERT(varchar, ValueLow) IS NOT NULL AND
CONVERT(varchar, ValueHi) IS NOT NULL AND
Spec = 1 THEN ' (Range: '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueLow,0))) + '' - '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueHi,0))) + )'
ELSE ''''
END
ELSE WOtask.TaskAction + CASE
WHEN CONVERT(varchar, ValueLow) IS NOT NULL AND
CONVERT(varchar, ValueHi) IS NOT NULL AND
Spec = 1 THEN ' (Range: '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueLow,0))) + '' - '' + CONVERT(VARCHAR,CONVERT(FLOAT,ISNULL(ValueHi,0))) + )'
ELSE ''''
END
END,
Rate,
Measurement,
Initials,
Fail,
Complete,
Header,
LineStyle,
WOtask.Comments,
WOtask.NotApplicable,
WOTask.Photo1,
WOTask.Photo2
FROM WOtask WITH (NOLOCK)
LEFT OUTER JOIN Asset WITH (NOLOCK)
ON Asset.AssetPK = WOTask.AssetPK
LEFT OUTER JOIN AssetSpecification
ON AssetSpecification.PK = WOTask.AssetSpecificationPK
WHERE (WOPK IN (SELECT
WOPK
FROM WO WITH (NOLOCK)
LEFT OUTER JOIN Asset WITH (NOLOCK)
ON Asset.AssetPK = WO.AssetPK
LEFT OUTER JOIN AssetHierarchy WITH (NOLOCK)
ON AssetHierarchy.AssetPK = WO.AssetPK
WHERE WO.WOPK = 10109)
)
ORDER BY WOPK, TaskNo
now please check my output and error
please help to solve this issue. Thanks in Advance.
As noted in comments, use ELSE '' instead of ELSE ''''. The reason is that within a pair of single quotes, then '' tells SQL to escape a single quote into your output.
For instance, to show the output User's, you would need SELECT 'User''s'.

CASE statement: Inconsistent conversion fail error - varchar to int

SELECT
CASE
WHEN Employees.first_name IS NULL
OR Employees.first_name = 'x' THEN Employees.last_name
WHEN Employees.credentials IS NULL THEN Employees.last_name + ', ' + Employees.first_name
ELSE Employees.last_name + ', ' + Employees.first_name + ' - ' + Employees.credentials
END,
Employees.num3,
Employees.address1 + ' ' + Employees.city + ', ' + Employees.state + ' ' + Employees.zip,
Employees.work_phone,
CASE
WHEN Clients.age <= 18 THEN 'Youth'
ELSE 'Adult'
END,
Clients.client_id,
Clients.last_name + ', ' + Clients.first_name,
ClientVisit.cptcode,
ClientVisit.visittype,
ClientVisit.rev_timeout,
ClientVisit.timein,
ClientVisit.duration,
SUM(CASE
WHEN ClientVisit.cptcode = 90791 THEN 200
WHEN ClientVisit.comb_units = 1 THEN 85.67
ELSE ClientVisit.comb_units * 21.4175
END),
DATEDIFF(d, ClientVisit.rev_timeout, ClientVisit.signature_datetime)
FROM dbo.ClientVisit
INNER JOIN dbo.Employees
ON (
ClientVisit.by_emp_id = Employees.emp_id
)
INNER JOIN dbo.Programs
ON (
ClientVisit.program_id = Programs.program_id
)
INNER JOIN dbo.Clients
ON (
Clients.client_id = ClientVisit.client_id
)
WHERE (
ClientVisit.rev_timeout BETWEEN '20160401 11:40:00.000' AND '20160415 11:40:16.000'
AND Programs.program_desc IN ('Off Panel')
AND ClientVisit.non_billable = 0
AND ClientVisit.cptcode NOT IN ('00000', '0124', '100', '1001', '101', '102', '103', '80100', '9079', '99999')
AND Employees.num3 IS NOT NULL
)
GROUP BY
CASE
WHEN Clients.age <= 18 THEN 'Youth'
ELSE 'Adult'
END,
CASE
WHEN Employees.first_name IS NULL
OR Employees.first_name = 'x' THEN Employees.last_name
WHEN Employees.credentials IS NULL THEN Employees.last_name + ', ' + Employees.first_name
ELSE Employees.last_name + ', ' + Employees.first_name + ' - ' + Employees.credentials
END,
DATEDIFF(d, ClientVisit.rev_timeout, ClientVisit.signature_datetime),
ClientVisit.cptcode,
Clients.last_name + ', ' + Clients.first_name,
Clients.client_id,
Employees.address1 + ' ' + Employees.city + ', ' + Employees.state + ' ' + Employees.zip,
Employees.work_phone,
ClientVisit.duration,
ClientVisit.visittype,
ClientVisit.rev_timeout,
ClientVisit.timein,
Employees.num3
Gives me the Error:
Conversion failed when converting the varchar value 'H2019' to data
type int.
I'm unable to locate specifically where this conversion is taking place and what could be a possible fix.
EDIT: Located problem in cptcode column which has alphanumeric entries. However, changing date ranges in WHERE clause gives results for some dates and not for others.
when you use
"ClientVisit"."cptcode" = 90791
the data type of 90791 will be integer. If you replace it with
"ClientVisit"."cptcode" = '90791'
both sides of the equation will be characters. You can also do something like:
"ClientVisit"."cptcode" = CAST(90791 AS VARCHAR(20))
The reasons for your problem is that SQL Server will do an implicit conversion. In this case to integer as Integer has a higher Data Type Precedence than (n)(var)char data types.
Of course I do not know your data but I guess there are data ranges where there is only numeric values for cptcode. So your code will work for them but not if you hit something like e.g. H006
Hope that helps ;-)
Comment out all the colums in the select segment and start ucommenting them one by one while executing the select each time. When you uncomment the problematic line, you'll find the source of the error.
BTW: I'm guessing the problem is in "ClientVisit"."cptcode" = 90791.

Case When + Concatenate from Two Tables

I need to concatenate two fields from different tables, based on the results of a case when. This is what I have so far -
Select
CASE WHEN [Record] = 'Criteria' then (dbo.[Table A].[Field] + ' ' + dbo.[Table B].[Field]) AS 'Name'
Else ' '
INNER JOIN dbo.[Table] ON dbo.[Table].[Field] = dbo.[Table].[Field]
From [Table]
But when I run this, I keep getting the error
Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword
'AS'.
I don't know if my statement is just totally wrong or I have missed something in it.
Thanks
Select
CASE WHEN [Record] = 'Criteria' then (dbo.[Table A].[Field] + ' ' + dbo.[Table B].[Field])
Else ' '
end AS 'Name'
From [Table]
INNER JOIN dbo.[Table] ON dbo.[Table].[Field] = dbo.[Table].[Field]
Then problem with your case statement;
CASE WHEN [Record] = 'Criteria' then (dbo.[Table A].[Field] + ' ' + dbo.[Table B].[Field])
Else ' ' end AS 'Name'
Keep in mind that using + to concatenating string you will get NULL if tab_a.[Field] or tab_b.[Field] is NULL.
Second use aliases to table names.
SELECT
[Name] = CASE
WHEN [Record] = 'Criteria' THEN (tab_a.[Field] + ' ' + tab_b.[Field])
ELSE ' '
END
FROM [dbo].[Table A] AS tab_a
JOIN [dbo].[Table B] AS tab_b
ON tab_a.[Field] = tab_b.[Field]

Sql - How to add condition on fields when inserting them into a table?

I need to insert strings in an sql table, where I have to add condition. For example:
SELECT ii.Terminating_Item_Site_ID,
ii.Originating_Item_Site_ID,
loc.ServiceAddress,
loc.ServiceCity,
loc.ServiceState,
(ii.Originating_Item_Site_ID + ' - ' + loc.ServiceAddress + ', ' + loc.ServiceCity + ', ' + loc.ServiceState) AS OrigSite
FROM tblItemInventory ii
LEFT OUTER JOIN tblServiceLocation AS loc ON loc1.ServiceLocationID = ii.Originating_Item_Site_ID
I need to put a condition when inserting the field OrigSite, so if ii.Originating_Item_Site_ID or loc.ServiceAddress or loc.ServiceCity or loc.ServiceState is null, I don't need to include it so I replace it with ''.
What is happening is that if any of the above fields is null, OrigSite is becoming null as well.
I have tried to use WHEN but I couldn't manage it.
I am using SQL Server 2008 R2.
Can anyone help?
When you concatenate string and 1 of the string is null the concatenated result is also null. You can use isnull('string','') on each part to avoid that behavior. Here is the code example:
SELECT ii.Terminating_Item_Site_ID,
ii.Originating_Item_Site_ID,
loc.ServiceAddress,
loc.ServiceCity,
loc.ServiceState,
(ISNULL(ii.Originating_Item_Site_ID,'')
+ ' - ' + ISNULL(loc.ServiceAddress,'')
+ ', ' + ISNULL(loc.ServiceCity,'')
+ ', ' + ISNULL(loc.ServiceState,'')) AS OrigSite
FROM tblItemInventory ii
LEFT OUTER JOIN tblServiceLocation AS loc ON loc1.ServiceLocationID = ii.Originating_Item
SELECT ii.Terminating_Item_Site_ID,
coalesce(ii.Originating_Item_Site_ID,''),
coalesce(loc.ServiceAddress,''),
coalesce(loc.ServiceCity,''),
coalesce(loc.ServiceState,''),
(coalesce(ii.Originating_Item_Site_ID,'') + ' - ' + coalesce(loc.ServiceAddress,'') + ', ' + coalesce(loc.ServiceCity,'') + ', ' + coalesce(loc.ServiceState,'')) AS OrigSite
FROM tblItemInventory ii
LEFT OUTER JOIN tblServiceLocation AS loc ON loc1.ServiceLocationID = ii.Originating_Item_Site_ID
ISNULL is a system function that replaces null values with a predifined value.
Colasce is another one like ISNULL But Coalesce is a part of standard sql.
ISNULL is T-sql specific.
Be more standard be more portable.
SELECT ii.Terminating_Item_Site_ID,
isnull(ii.Originating_Item_Site_ID,''),
isnull(loc.ServiceAddress,''),
isnull(loc.ServiceCity,''),
isnull(loc.ServiceState,''),
(isnull((ii.Originating_Item_Site_ID + ' - ' + isnull(loc.ServiceAddress,'') + ', ' + isnull(loc.ServiceCity,'') + ', ' + isnull(loc.ServiceState,'')) AS OrigSite
FROM tblItemInventory ii
LEFT OUTER JOIN tblServiceLocation AS loc ON loc1.ServiceLocationID = ii.Originating_Item_Site_ID