sql server 2012 : Incorrect syntax near the keyword 'else' - sql

I receive this error and I cant find out why.
case when FormFields.fieldtype like '%date%'
then 'not' + fieldname + ' is null and ( convert(datetime,'
+ fieldname +',103) < '
+ coalesce(str(FormFields.MinDate),'1/1/1900') + ')'
+ ' or ( convert(datetime,' + fieldname +',103) > '
+ coalesce(str(FormFields.MaxDate), '1/1/2200') + ')'
+
else
'not '+ fieldname + ' is null and ( convert(float,'+ fieldname+') <'
+ coalesce(str(FormFields.MinValue),'-99999999')
+ ' or convert(float,'+ fieldname+') >'
+ coalesce(str(FormFields.MaxValue),'99999999') +')'
+
end
previous code without any error:
'not '+ fieldname + ' is null and ( convert(float,'+ fieldname+') <'
+ coalesce(str(FormFields.MinValue),'-99999999')
+ ' or convert(float,'+ fieldname+') >'
+ coalesce(str(FormFields.MaxValue),'99999999') +')'
+
I just wanted to add another case

You have 2 extra + in your query, 1 in the end of the THEN part, another in end of the ELSE part. If you need to combine CASE expression with another string, use + after END. Try in following:
case when FormFields.fieldtype like '%date%'
then 'not' + fieldname + ' is null and ( convert(datetime,'
+ fieldname +',103) < '
+ coalesce(str(FormFields.MinDate),'1/1/1900') + ')'
+ ' or ( convert(datetime,' + fieldname +',103) > '
+ coalesce(str(FormFields.MaxDate), '1/1/2200') + ')'
else
'not '+ fieldname + ' is null and ( convert(float,'+ fieldname+') <'
+ coalesce(str(FormFields.MinValue),'-99999999')
+ ' or convert(float,'+ fieldname+') >'
+ coalesce(str(FormFields.MaxValue),'99999999') +')'
end
+ 'Any string after CASE expression'

Related

SQL cannot convert an int to a varchar(15) value and throws: Conversion failed when converting the varchar value ' LBS' to data type int

I am working on a SQL project that is pulling data from many tables to list them out in an email body. In the body of my email, I am pulling int values that are throwing exceptions because the body needs to eventually be a nvarchar(max). Different types of conversion have not worked for me yet.
This is SQL running on Microsoft SQL Server Management Studio. I have tried leaving the int unconverted, and a few different conversion methods I have seen elsewhere.
In the examples, wtpc.Reg_No is a varchar and wtpc.Shipment_Net_Weight is an int.
'Body' =
...
+ 'Net: ' +
CASE
WHEN wtpc.Reg_No IS NOT NULL THEN wtpc.Shipment_Net_Weight
ELSE '0'
END
+ ' LBS'
+ 'Gross:
...
Results in: Conversion failed when converting the varchar value ' LBS' to data type int.
'Body' =
...
+ 'Net: ' +
CASE
WHEN wtpc.Reg_No IS NOT NULL THEN str(wtpc.Shipment_Net_Weight)
ELSE '0'
END
+ ' LBS'
+ 'Gross:
...
Results in: Error converting data type varchar to float.
'Body' =
...
+ 'Net: ' +
CASE
ELSE wtpc.Reg_No IS NOT NULL THEN
CONVERT(INT,
CASE
WHEN IsNumeric(CONVERT(VARCHAR(15), wtpc.Shipment_Net_Weight)) = 1
THEN CONVERT(VARCHAR(15),wtpc.Shipment_Net_Weight)
ELSE 0
END)
ELSE '0'
END
+ ' LBS'
+ 'Gross:
...
Results in: Conversion failed when converting the varchar value ' LBS' to data type int.
This is lifted from this StackOverflow Question
Here is a more complete view:
Declare #TempResults1 table(
ThisSubject nvarchar(max),
ThisTo nvarchar(max),
ThisCC nvarchar(max),
ThisBody nvarchar(max),
ThisBody2 nvarchar(max))
Insert into #TempResults1
Select
'Subject' =
isnull( #ShipmentNoString, '') + ' - ' + shpr.Last_Name + ', ' + shpr.First_Name + isnull(' - ' + #ModeString, '')
+ case
when cstm.broker_agent = -1 then ' - Foreign Port Agent Pre-Alert'
else ' - Port Agent Pre-Alert'
end,
... [To and CC are set here similiar to how the subject is set]
'Body' =
+ 'To: ' + vncb.Vendor_Name
+ 'Attn: ' +
case
when #GsaUsContact is not null then #GsaUsContact
else #GsaForContact
end
+ 'From: ' + usrs.Name
+ 'Date: ' + format(getdate(), 'ddMMyy')
... [More similar code]
+ 'Mode: ' + mode.Mode
+ 'Net: ' +
case
when wtpc.Reg_No is not null then CAST( wtpc.Shipment_Net_Weight AS varchar(15))
else '0'
end
+ ' LBS'
+ 'Gross: ' +
case
when wtpc.Reg_No is not null then CAST( wtpc.Shipment_Gross as varchar(15))
else '0'
end
+ ' 2LBS'
+ 'Cube: ' + isnull(wtpc.Shipment_CFT, '0') + ' CFT'
+ 'Pieces: ' +
case
when wtpc.Reg_No is not null then CAST(wtpc.Shipment_Piece_Count, varchar(15))
else '0'
end
+ ' PCS'
+ '<BR>'
+ 'OBL/AWB #: ' + asea.Mawb_Obl_No
...[More code like above with varchars]
+isnull('<b> Please send all correspondence to: ' + usrs.email + '.</b>', '')
,Body2 = null
Found the fix:
isnull( convert(varchar(50), wtpc.Shipment_Net_Weight), '')
There were no matching cases, but the errors didn't show this, kinda goofy! Thank you for all the help everyone!

using sql - Is not null in a select statement

I can't seem to figure out how to use the opposite of isnull or ifnull statements in sql. I need to say if a.Error1 is not null -- then print the ' - ' and the + CHAR(13)+CHAR(10). Basically There should be no dash or no new line break if the a.Error1 comes back null. So print the information if the field isn't null.
select a. ....
' - ' + a.Error1 + CHAR(13)+CHAR(10) +
' - ' + a.Error2 + CHAR(13)+CHAR(10) +
' - ' + a.Error3 + CHAR(13)+CHAR(10) +
' - ' + a.Error4 + CHAR(13)+CHAR(10) +
' - ' + a.Error5 + CHAR(13)+CHAR(10) +
' - ' + a.Error6 as 'error_message'
...
from table1 a
For example if for a given record error1, 2 and 5 returned output I would like the output to be as follows:
- Error1: There was a ...
- Error2: ....
- Error5: The data was ...
If no errors existed for that row it should simply be an empty/null field.
You can use CASE:
SELECT a. ....
(CASE WHEN a.Error1 IS NOT NULL
THEN ' - ' + a.Error1 + CHAR(13)+CHAR(10)
ELSE ''
END) +
(CASE WHEN a.Error2 IS NOT NULL
THEN ' - ' + a.Error2 + CHAR(13)+CHAR(10)
ELSE ''
END) +
(CASE WHEN a.Error3 IS NOT NULL
THEN ' - ' + a.Error3 + CHAR(13)+CHAR(10)
ELSE ''
END) +
...etc
Yes! i know i'm like 5 years too late but i too enountered this problem.
It's weird how it doesn't exist some kind of !ISNULL() but whatever.
Try this for a cleaner code:
select a. ....
IIF(a.Error1 IS NOT NULL, ' - ' + a.Error1 + CHAR(13)+CHAR(10) , '') as Error1,
IIF(a.Error1 IS NOT NULL, ' - ' + a.Error1 + CHAR(13)+CHAR(10) , '') as Error2
from table1 a
Learn more about IIF() function : SQL Server IIF Function
The COALESCE function does what you want here. The result of COALESCE is the first NOT NULL value it is passed. Below we use '', which is distinct from NULL so that the outer + is always applied to NOT NULL strings.
e.g.
select a. ....
COALESCE( ' - ' + a.Error1 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error2 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error3 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error4 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error5 + CHAR(13)+CHAR(10), '' ) +
COALESCE( ' - ' + a.Error6 , '' ) as 'error_message'
...
from table1 a
SELECT (CASE WHEN a.Error1 IS NOT NULL
THEN ' - ' + a.Error1 + CHAR(13)+CHAR(10) +
ELSE a.Error1
END) +
(CASE WHEN a.Error2 IS NOT NULL
THEN ' - ' + a.Error2 + CHAR(13)+CHAR(10) +
ELSE a.Error2
END) +
.....etc

AS NewCompoundField - Concatenating values which may be NULL

I have the following T-SQL query;
SELECT
Site.Address1 + CHAR(13) + Site.Address2 + CHAR(13) +
Site.Address3 + CHAR(13) + Site.Town + CHAR(13) +
Site.eCounty AS SiteAddress
FROM Site
If any of the Site.AddressX fields making up SiteAddress are NULL, then SiteAddress is itself NULL. I would like a Site.AddressX field and it's following new line character to be ignored if it is NULL.
I have tried adding a CASE statement for a single field and it's new line character, but have not been able to get it to work.
SELECT
(CASE WHEN (Site.Address1 IS NULL) THEN '' ELSE Site.Address1 + CHAR(10)) +
Site.Address2 + CHAR(13) +
Site.Address3 + CHAR(13) + Site.Town + CHAR(13) +
Site.eCounty AS SiteAddress
FROM Site
How might I go about doing this?
Try this:
SELECT
COALESCE([Site].Address1 + CHAR(13), '') +
COALESCE([Site].Address2 + CHAR(13), '') +
COALESCE([Site].Address3 + CHAR(13), '') +
COALESCE([Site].Town + CHAR(13), '') +
[Site].eCounty AS SiteAddress
FROM [Site]
Try this
SELECT
CASE WHEN Site.Address1 IS NULL THEN ''
ELSE Site.Address1 + CHAR(10) +
Site.Address2 + CHAR(13) +
Site.Address3 + CHAR(13) + Site.Town + CHAR(13) +
Site.eCounty END AS SiteAddress
FROM SITE Site

How to write/append text to the bottom of n SQL script?

I have the need to add/append text(SQL) to the bottom of an existing script.
I have a STORED PROCEDURE that generates INSERT statements for me. They are quit allot, so at the moment i copy and past them in the desired scripts.
This is basically what the SQL looks like:
SELECT '' + CHAR(13) + CHAR(10) + 'EXECUTE [procSystemAppEntity_InsertOrUpdate] ' + CHAR(13) + CHAR(10) + ' #SystemUID = #SystemUID' + CHAR(13) + CHAR(10)
+ ',#SystemAppCode = #SystemAppCode' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityTypeCode = N''' + saet.[SystemAppEntityTypeCode] + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityUID = '''+ CAST((SELECT NEWID()) AS nvarchar(max)) + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityCode = ''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityName = N''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#TableName = N''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#TableKeyColumnName = N''' + tab.name + 'ID''' + CHAR(13) + CHAR(10)
+ ',#TableKeyCodeColumnName = N''' + tab.name + 'Code''' + CHAR(13) + CHAR(10)
+ ',#ManagedAssemblyName = N''' + CASE WHEN #SystemAppEntityManagedAssemblyName IS NULL THEN '' ELSE #SystemAppEntityManagedAssemblyName END + '''' + CHAR(13) + CHAR(10)
+ ', #ManagedNamespace = N''' + CASE WHEN #SystemAppEntityManagedNamespace IS NULL THEN '' ELSE #SystemAppEntityManagedNamespace END + '''' + CHAR(13) + CHAR(10)
+ ', #ManagedClassName = ''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ', #IsMultiple = ' + CAST(#IsMultiple AS varchar(1)) + CHAR(13) + CHAR(10)
+ ', #IsCodeGenerated = 1' + CHAR(13) + CHAR(10)
+ ', #IsActive = 1' + CHAR(13) + CHAR(10)
+ ', #SystemAppUserID = #CreationSystemAppUserID ' + CHAR(13) + CHAR(10) + '; '
FROM sys.tables tab INNER JOIN
[SystemAppEntityType] saet ON saet.[IsMultipleEntity] = CASE WHEN RIGHT(tab.name, 1) = 's' THEN 1 ELSE 0 END AND saet.[IsNavigationEntity] = 0 AND saet.IsSystemEntity = CASE WHEN LEFT(tab.name, 3) = 'Sys' THEN 1 ELSE 0 END
WHERE (tab.name NOT IN (SELECT e.[TableName] FROM [SystemAppEntity] e))
AND (tab.name = #Code)
With an output of:
EXECUTE [procSystemAppEntity_InsertOrUpdate]
#SystemUID = #SystemUID
,#SystemAppCode = #SystemAppCode
,#SystemAppEntityTypeCode = N'App-S'
,#SystemAppEntityUID = '11E347C7-7E69-4555-A6F0-2AFE142FC25F'
,#SystemAppEntityCode = 'Revision'
,#SystemAppEntityName = N'Revision'
,#TableName = N'Revision'
,#TableKeyColumnName = N'RevisionID'
,#TableKeyCodeColumnName = N'RevisionCode'
,#ManagedAssemblyName = N'SomeManagedAssemblyName '
, #ManagedNamespace = N'SomeManagedNamespace '
, #ManagedClassName = 'Revision'
, #IsMultiple = 0
, #IsCodeGenerated = 1
, #IsIntegratedToStaging = 1
, #IsActive = 1
, #SystemAppUserID = #CreationSystemAppUserID
;
That being said, is there a way that i can maybe write/append the Output statements directly to the desired script?
I just want it to add to the bottom of the script. Is this possible and if so, how would i achive this?
SELECT '' + CHAR(13) + CHAR(10) + 'EXECUTE [procSystemAppEntity_InsertOrUpdate] ' + CHAR(13) + CHAR(10) + ' #SystemUID = #SystemUID' + CHAR(13) + CHAR(10)
+ ',#SystemAppCode = #SystemAppCode' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityTypeCode = N''' + saet.[SystemAppEntityTypeCode] + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityUID = '''+ CAST((SELECT NEWID()) AS nvarchar(max)) + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityCode = ''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityName = N''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#TableName = N''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#TableKeyColumnName = N''' + tab.name + 'ID''' + CHAR(13) + CHAR(10)
+ ',#TableKeyCodeColumnName = N''' + tab.name + 'Code''' + CHAR(13) + CHAR(10)
+ ',#ManagedAssemblyName = N''' + CASE WHEN #SystemAppEntityManagedAssemblyName IS NULL THEN '' ELSE #SystemAppEntityManagedAssemblyName END + '''' + CHAR(13) + CHAR(10)
+ ', #ManagedNamespace = N''' + CASE WHEN #SystemAppEntityManagedNamespace IS NULL THEN '' ELSE #SystemAppEntityManagedNamespace END + '''' + CHAR(13) + CHAR(10)
+ ', #ManagedClassName = ''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ', #IsMultiple = ' + CAST(#IsMultiple AS varchar(1)) + CHAR(13) + CHAR(10)
+ ', #IsCodeGenerated = 1' + CHAR(13) + CHAR(10)
+ ', #IsActive = 1' + CHAR(13) + CHAR(10)
+ ', #SystemAppUserID = #CreationSystemAppUserID ' + CHAR(13) + CHAR(10) + ';
Insert into table(...) ;'
FROM sys.tables tab INNER JOIN
[SystemAppEntityType] saet ON saet.[IsMultipleEntity] = CASE WHEN RIGHT(tab.name, 1) = 's' THEN 1 ELSE 0 END AND saet.[IsNavigationEntity] = 0 AND saet.IsSystemEntity = CASE WHEN LEFT(tab.name, 3) = 'Sys' THEN 1 ELSE 0 END
WHERE (tab.name NOT IN (SELECT e.[TableName] FROM [SystemAppEntity] e))
AND (tab.name = #Code)
What version of SQL Server are you using?
If you are using SQL Server 2008+ then you can make generate the INSERT scripts via Generate Script utility itself.
In SQL Server 2005 or before (I have tried in SQL 2K also) then there is a pretty good stroed proc which can generate the INSERT script for a given table. Check out http://vyaskn.tripod.com/code/generate_inserts.txt

Arithmetic overflow error converting varchar to data type numeric

Hi i have a query below which creates insert script for me. the column TotalPremiumValue has datatype Decimal(5,2). when i execute my query i am getting the following error: Arithmetic overflow error converting varchar to data type numeric. can anybody help me?
SELECT 'IF NOT EXISTS(SELECT 1 FROM Lkup.TotalPremium WHERE [TotalPremiumValue]= '''+[TotalPremiumValue]+''')
INSERT INTO Lkup.TotalPremium ' +
'(' +
'[TotalPremiumValue],' +
'[EffectiveDate]' +
')' +
'VALUES (' +
CASE WHEN [TotalPremiumValue] IS NULL THEN 'NULL' ELSE CONVERT(VARCHAR(40), [TotalPremiumValue]) END + ', ' +
CASE WHEN [EffectiveDate] IS NULL THEN 'NULL' ELSE 'CONVERT(DATETIME, ' + master.sys.fn_varbintohexstr (CONVERT(BINARY(8), [EffectiveDate])) + ')' END + ', ' +
')'
FROM Lkup.TotalPremium
Thanks
Perhaps try recasting the result as a decimal(5,2)? I added the call into a portion of your code and pasted the section below. You could also shrink that varchar(40) down to a varchar(6), which would hold all 5 numbers plus the decimal point.
'VALUES ( CAST(' +
CASE WHEN [TotalPremiumValue] IS NULL THEN 'NULL' ELSE CONVERT(VARCHAR(40), [TotalPremiumValue]) END + ' AS DECIMAL(5,2)), ' +
CASE WHEN [EffectiveDate] IS NULL THEN 'NULL' ELSE 'CONVERT(DATETIME, ' + master.sys.fn_varbintohexstr (CONVERT(BINARY(8), [EffectiveDate])) + ')' END + ', ' +
')'
Please try the below query
SELECT
'IF EXISTS(SELECT 1 FROM Lkup WHERE [TotalPremiumValue] = ' + CONVERT(varchar(50), [TotalPremiumValue]) + ')
INSERT INTO Lkup ' +
'(' +
'[TotalPremiumValue]' +
')' +
'VALUES (' +
case when CONVERT(varchar(50),[TotalPremiumValue]) IS NULL then 'null' else CONVERT(varchar(50),TotalPremiumValue) end +
')'
FROM Lkup