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

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,

Related

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.

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

SELECT statement issue - Joining of data of different fields in one cell of Gridview

I am using following SELECT statement for Gridview:
SelectCommand="SELECT ID, Date, Train, I_R, Dir_Ind, Detn, Rly, DiV, Loco, Shed, locoClass, loco_type,
(maj_sch_type + ','+ ' ' + maj_sch_place +',' +' '+ (CAST(maj_sch_dt as VARCHAR(11)) + ' '+'/'
+ ' ' + min_sch_type +',' + ' ' + min_sch_place + ',' + ' '+(CAST(min_sch_dt as VARCHAR (11))) )) as "major",
Equipt, I_R, reason
FROM PunctualityMain Order by Date ASC"
With the above, I am getting results in single cell from 6 (3 + 3) different fields of SQL data as
POH, KPA, Jan 2 2012 / IB, Shed, Apr 18 2012
Issue is this that whenever data in any group of 3 fields (before or after '/') is blank, Gridview cell is remain completely blank. If both group of fields having data than Gridview dispaly is OK as mentioned above. Can SELECT statement be modified for showing data in Gridview with any one group of fields are empty?
If you try to concatenate a null string with a non-null string, the result will be null.
Select NULL + 'test'
this will return NULL.
Also, I think your code didn't copy paste extremely well into your question, but you need to use the ISNULL() function. I think you can get the point. You'll probably have to clean up the code a bit for it to run. Just wrap every field that you are concatenating with ISNULL(MyField, '')
SELECT
ID,
Date,
Train,
I_R,
Dir_Ind,
Detn,
Rly,
DiV,
Loco,
Shed,
locoClass,
loco_type,
(isnull(maj_sch_type, '') + ', ' + isnull(maj_sch_place, '') +', '+ (isnull(CAST(maj_sch_dt as VARCHAR(11), '')) + ' / ' + isnull(min_sch_type, '') +', ' + isnull(min_sch_place, '') + ', '+ (isnull(CAST(min_sch_dt as VARCHAR (11)), '')) )) as "major",
Equipt,
I_R,
reason
FROM PunctualityMain
Order by Date ASC
Reference
IsNull

SQL print a space between concat statements

Concatenating two columns together, Just want them to be displaying together in column with a space between the two numbers. It keeps adding the two numbers together. One is a bigint other is a smallint.Will be displayed in an SSRS report eventually but right now just using SQL to query the data
(NBR +''+ ACCT_NBR) as acct,
Though you didn't mention the database, try
MySQL
concat(NBR,' ',ACCT_NBR) as acct
SQL Server
CAST(NBR AS VARCHAR)+' '+CAST(ACCT_NBR AS VARCHAR) as acct
You don't mention what flavor of SQL you're using, but depending, you may need to convert the values to strings first. For SQLSever...
(Cast(NBR as varchar(20)) + ' ' + Cast(ACCT_NBR as varchar(20))) as acct,
I know this post is already answered and is correct. But would like to post the below answer because from SQL Server 2017 onwards, this is too easy and someoen might find this helpful in future.
CONCAT_WS(CHAR(10),Cast(NBR as varchar(20)) ,Cast(ACCT_NBR as varchar(20))) as acct
CHAR(10) can be for space in SQL SERVER. You can replace CHAR(10) with any separator you like to. For example,
CONCAT_WS(',',Cast(NBR as varchar(20)) ,Cast(ACCT_NBR as varchar(20))) as acct
the above query will add the separator ',' between each strings being concatenated.
If its an Oracle Database, try
NBR || ' ' || ACCT_NBR as acct
Stuff(Coalesce(', ' + [Address1], '') + Coalesce(', ' + [Address2], '') + Coalesce(', ' + [City], '') + Coalesce(', ' + [State], '') + Coalesce(', ' + [Country], '') +Coalesce('-' + [Zip], ''), 1, 1, '') AS [Address] FROM Customers
I know I'm 7 years late, but felt like I should give this a try.
(NBR +space(5) + ACCT_NBR) as acct
This will add 5 whitespaces between the 2 concatenated items.
My example on how I tested was as follows:
select
+ N'(Contactname: '+ contactname + space(5) + N'(Company_Name: ' + companyname + N')' + N'(Contact_Title: ' + contacttitle + N')'
from Sales.Customers
In Teradata SQL you can use the below. It will always pull the last 3 days.
WHERE create_ts BETWEEN (DATE -3 || ' ' || '00:00:00') AND (DATE -1 || ' ' || '23:59:59')

Complex SQL CASE WHEN

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] ,