Reduce multiple if else statement - sql-server

I have the following 5 variables to check for a condition.
Example:
DECLARE #Col1 VARCHAR(10) = ''
DECLARE #Col2 VARCHAR(10) = ''
DECLARE #Col3 VARCHAR(10) = ''
DECLARE #Col4 VARCHAR(10) = ''
DECLARE #Col5 VARCHAR(10) = ''
DECLARE #String VARCHAR(MAX)
IF #Col1 = '' AND #Col2 = '' AND #Col3 = '' AND #Col4 = '' AND #Col5 = ''
BEGIN
SET #String = ''
END
ELSE IF #Col1 <> '' AND #Col2 = '' AND #Col3 = '' AND #Col4 = '' AND #Col5 = ''
BEGIN
SET #String = '#Col1'
END
ELSE IF #Col1 = '' AND #Col2 <> '' AND #Col3 = '' AND #Col4 = '' AND #Col5 = ''
BEGIN
SET #String = '#Col2'
END
ELSE IF #Col1 = '' AND #Col2 = '' AND #Col3 <> '' AND #Col4 = '' AND #Col5 = ''
BEGIN
SET #String = '#Col3'
END
ELSE IF #Col1 = '' AND #Col2 = '' AND #Col3 = '' AND #Col4 <> '' AND #Col5 = ''
BEGIN
SET #String = '#Col4'
END
.....
.....
.....
As the above conditions show, there are many probabilities.
How can I reduce the occurrences of multiple if conditions?

You can use CASE WHEN:
SELECT #String = CASE
WHEN #Col1 = '' AND #Col2 = '' AND #Col3 = '' AND #Col4 = '' AND #Col5 = '' THEN ''
WHEN #Col1 <> '' AND #Col2 = '' AND #Col3 = '' AND #Col4 = '' AND #Col5 = '' THEN '#Col1'
WHEN #Col1 = '' AND #Col2 <> '' AND #Col3 = '' AND #Col4 = '' AND #Col5 = '' THEN '#Col2'
WHEN #Col1 = '' AND #Col2 = '' AND #Col3 <> '' AND #Col4 = '' AND #Col5 = '' THEN '#Col3'
WHEN #Col1 = '' AND #Col2 = '' AND #Col3 = '' AND #Col4 <> '' AND #Col5 = '' THEN '#Col4'
ELSE NULL
END
SQL Server 2012+:
SELECT #String = COALESCE(IIF(#Col1 <> '', '#Col1', NULL),
IIF(#Col2 <> '', '#Col2', NULL),
IIF(#Col3 <> '', '#Col3', NULL),
IIF(#Col4 <> '', '#Col4', '' ));
EDIT:
DECLARE #Col1 VARCHAR(10) = ''
DECLARE #Col2 VARCHAR(10) = ''
DECLARE #Col3 VARCHAR(10) = ''
DECLARE #Col4 VARCHAR(10) = ''
DECLARE #Col5 VARCHAR(10) = ''
DECLARE #String VARCHAR(MAX) = '';
IF #col1 <> ''
SET #String += '#col1';
IF #col2 <> ''
SET #String += '#col2';
IF #col3 <> ''
SET #String += '#col3';
...
IF #coln <> ''
SET #String += '#coln';

I would like to help as well, sorry for a different approach.
I took your case as something that can be stacked and I arrived at this.
DECLARE #Col1 VARCHAR(10) = 'test'
DECLARE #Col2 VARCHAR(10) = ''
DECLARE #Col3 VARCHAR(10) = 'tet'
DECLARE #Col4 VARCHAR(10) = ''
DECLARE #Col5 VARCHAR(10) = 't'
DECLARE #String VARCHAR(MAX)
CREATE TABLE #cols (ColName NVARCHAR(150), ColVal NVARCHAR(150))
INSERT INTO #cols VALUES ('#Col1',#Col1),('#Col2',#Col2),('#Col3',#Col3),('#Col4',#Col4),('#Col5',#Col5)
-- if you want to just concatenate things without a delimiter, you can do this
SET #String = (SELECT ColName AS [text()] FROM #cols WHERE ColVal != '' FOR XML PATH(''))
SELECT #String
-- output #Col1#Col3#Col5
-- if you want to concatenate things with a delimiter, you can do this
SET #String = (SELECT ColName + ', ' AS [text()] FROM #cols WHERE ColVal != '' FOR XML PATH(''))
SELECT #String
-- output #Col1, #Col3, #Col5
DROP TABLE #cols
Hope this adds something to the idea. Please let me know if you have concerns.

You can do in one statement using case expressions:
SELECT #String = CASE WHEN #Col1 = '' THEN 'col1' ELSE '' END +
CASE WHEN #Col2 = '' THEN 'col2' ELSE '' END +
CASE WHEN #Col3 = '' THEN 'col3' ELSE '' END +
CASE WHEN #Col4 = '' THEN 'col4' ELSE '' END +
CASE WHEN #Col5 = '' THEN 'col5' ELSE '' END

Related

Prepare WHERE Clause string for given values

I have the following details to prepare string as shown below in the expected result.
Given:
DECLARE #VValue VARCHAR(MAX) = 'John Dee|Mak Don'
DECLARE #VColumns VARCHAR(MAX) = 'FName|LName'
DECLARE #VCondition VARCHAR(500) = 'OR'
DECLARE #VPattern VARCHAR(MAX) = 'Start|Exact'
DECLARE #VCheck VARCHAR(MAX) = '1|0'
DECLARE #String VARCHAR(MAX) = ''
Expected result:
(
ISNULL(PATINDEX(''John%'', FName), ''0'') > 0 AND
ISNULL(PATINDEX(''Dee%'', FName), ''0'') > 0
)
OR
(
ISNULL(PATINDEX(''Mak'', LName), ''0'') +
ISNULL(PATINDEX(''Don'', LName), ''0'') > 0
)
My attempt:
SET #VCondition = '|'+#VCondition;
SET #String = REPLACE('('+REPLACE(STUFF((SELECT N') '+DS3.Item+' (' + NCHAR(10) +
STUFF((SELECT
CASE WHEN DS4.Item = 'Start' AND DS5.Item = 0
THEN
N' + ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +'%'''''+ N',' + DSc.Item + N'),''''0'''')'
WHEN DS4.Item = 'Start' AND DS5.Item = 1
THEN
N' > 0 AND ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +'%'''''+ N',' + DSc.Item + N'),''''0'''')'
ELSE
''
END
+
CASE WHEN DS4.Item = 'Exact' AND DS5.Item = 0
THEN
N' + ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +''''''+ N',' + DSc.Item + N'),''''0'''')'
WHEN DS4.Item = 'Exact' AND DS5.Item = 1
THEN
N' > 0 AND ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +''''''+ N',' + DSc.Item + N'),''''0'''')'
ELSE ''
END
FROM dbo.f_split(DS1.Item,' ') DSn
CROSS APPLY dbo.f_split(DS2.Item,',') DSc
ORDER BY DSc.id, DSn.id
FOR XML PATH(N'')),1,4,N'')
FROM dbo.udf_split (#VValue,'|') DS1
CROSS APPLY dbo.udf_split (#VColumns,'|') DS2
CROSS APPLY dbo.udf_split (#VCondition,'|') DS3
CROSS APPLY dbo.udf_split (#VPattern,'|') DS4
CROSS APPLY dbo.udf_split (#VCheck, '|') DS5
WHERE DS1.id = DS2.id AND DS2.ID = DS3.ID AND DS3.ID = DS4.ID AND DS4.ID = DS5.ID
ORDER BY DS1.id
FOR XML PATH(N'')),1,9,N''),'>','>') + N') )','&gt;','>');
PRINT(#String);
But I'm getting the following result:
( AND
ISNULL(PATINDEX(''John%'', FName), ''0'') > 0 AND
ISNULL(PATINDEX(''Dee%'', FName), ''0'')) OR (
ISNULL(PATINDEX(''Mak'', LName), ''0'') +
ISNULL(PATINDEX(''Don'', LName), ''0'')) )
After many attempt, following does the job done.
Query:
DECLARE #VValue VARCHAR(MAX) = 'John Dee|Mak Don'
DECLARE #VColumns VARCHAR(MAX) = 'FName|LName'
DECLARE #VCondition VARCHAR(500) = 'OR'
DECLARE #VPattern VARCHAR(MAX) = 'Start|Exact'
DECLARE #VCheck VARCHAR(MAX) = '1|0'
DECLARE #String VARCHAR(MAX) = ''
SET #VCondition = '|'+#VCondition;
SET #String = REPLACE('('+STUFF((SELECT N' > 0 ) '+DS3.Item+' (' + NCHAR(10) +
REPLACE(STUFF((SELECT
CASE WHEN DS4.Item = 'Start' AND DS5.Item = 0
THEN
N' + ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +'%'''''+ N',' + DSc.Item + N'),''''0'''')'
WHEN DS4.Item = 'Start' AND DS5.Item = 1
THEN
N' > 0 AND ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +'%'''''+ N',' + DSc.Item + N'),''''0'''')'
ELSE
''
END
+
CASE WHEN DS4.Item = 'Exact' AND DS5.Item = 0
THEN
N' + ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +''''''+ N',' + DSc.Item + N'),''''0'''')'
WHEN DS4.Item = 'Exact' AND DS5.Item = 1
THEN
N' > 0 AND ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +''''''+ N',' + DSc.Item + N'),''''0'''')'
ELSE ''
END
FROM dbo.f_split(DS1.Item,' ') DSn
CROSS APPLY dbo.f_split(DS2.Item,',') DSc
ORDER BY DSc.id, DSn.id
FOR XML PATH(N'')),1,11,N''),'>','>')
FROM dbo.udf_split (#VValue,'|') DS1
CROSS APPLY dbo.udf_split (#VColumns,'|') DS2
CROSS APPLY dbo.udf_split (#VCondition,'|') DS3
CROSS APPLY dbo.udf_split (#VPattern,'|') DS4
CROSS APPLY dbo.udf_split (#VCheck, '|') DS5
WHERE DS1.id = DS2.id AND DS2.ID = DS3.ID AND DS3.ID = DS4.ID AND DS4.ID = DS5.ID
ORDER BY DS1.id
FOR XML PATH(N'')),1,13,N''),'>','>') + N' > 0 ) ';
PRINT(#String);
Output:
(
ISNULL(PATINDEX(''John%'',FName),''0'') > 0 AND
ISNULL(PATINDEX(''Dee%'',FName),''0'') > 0
)
OR
(
ISNULL(PATINDEX(''Mak'',LName),''0'') +
ISNULL(PATINDEX(''Don'',LName),''0'') > 0
)

Boolean conditions in SQL where clause

I wanted to write an sql query to fetch data as:
1. when param = 'all' it should list data across the table
2. when param = 'yes' it should list data where invoicenumber is not empty.
3. when param = 'no' it should list data where invoicenumber is empty.
i tried below query for yes and no
declare #invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
((#invoiced = 'yes') or (InvoiceNumber = ''))
and
((#invoiced = 'no') or (InvoiceNumber <> ''))
now i also want to incorporate all condition, could anyone suggest how could i achieve that
declare #invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
#invoiced = 'all'
OR
(#invoiced = 'yes' AND InvoiceNumber <> '')
OR
(#invoiced = 'no' AND InvoiceNumber = '')
Try this
declare #invoiced as nvarchar(10) = 'no'
select
*
from OrderSummary
where
(
#invoiced = 'all'
OR
(
#invoiced = 'yes'
AND
InvoiceNumber <> ''
)
OR
(
#invoiced = 'no'
AND
InvoiceNumber = ''
)
)
It should fulfill your requirement.
declare #invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
((#invoiced in ('all','no')) OR (#invoiced = 'yes' AND InvoiceNumber <> ''))
and
((#invoiced in ('all','yes')) OR (#invoiced = 'no' AND InvoiceNumber = ''))
and
(#invoiced in ('no','yes'))
declare #invoiced as nvarchar(10) = 'no'
select * from OrderSummary
where
((#invoiced = 'yes') and (InvoiceNumber <> '') )
or
((#invoiced = 'no') and ( (InvoiceNumber = '') or (InvoiceNumber = null)))
or (#invoiced = 'all')
Please update this query with above query.

SQL Logic to validate Parameter

I have parameter on sql , and I got an issue when it comes to this situation
declare #MonRemark varchar(10) = 's'
declare #ConfBy varchar(10)= 's'
declare #confstatus varchar(10)= 's'
declare #StatGD varchar(10)= ''
declare #StatGC varchar(50)= ''
declare #STATGTWO varchar(50)= ''
IF #MonRemark <> '' and (#ConfBy = '' OR #confstatus = '' and (#StatGD = '' or #StatGC = '' or #STATGTWO = '')) BEGIN
print 'a'
END
ELSE IF #ConfBy <> '' and (#MonRemark = '' OR #confstatus = '' AND (#StatGD = '' or #StatGC = '' or #STATGTWO = '')) BEGIN
print 'b'
END
ELSE IF #confstatus <> '' and #MonRemark = '' AND #ConfBy = '' AND (#StatGD = '' or #StatGC = '' or #STATGTWO = '') BEGIN
print 'c'
END
ELSE IF (#StatGD <> '' or #StatGC <> '' or #STATGTWO <> '') and #confstatus = '' AND #MonRemark = '' AND #ConfBy = '' BEGIN
print 'd'
END
ELSE BEGIN
print 'e'
END
if I filled parameter like what I write Above, I wish to get A , but it's always print E, is there any way to get A?
Change your condition. I think #Cyan and #JTR has provided enough explanation on why you get the value 'e'
Try like this, I have modified your condition to get the required results.
DECLARE #MonRemark VARCHAR(10) = 's'
DECLARE #ConfBy VARCHAR(10) = 's'
DECLARE #confstatus VARCHAR(10) = 's'
DECLARE #StatGD VARCHAR(10) = ''
DECLARE #StatGC VARCHAR(50) = ''
DECLARE #STATGTWO VARCHAR(50) = ''
IF #MonRemark <> ''
AND (
(
#ConfBy = ''
OR #confstatus = ''
)
OR (
#StatGD = ''
OR #StatGC = ''
OR #STATGTWO = ''
)
)
BEGIN
PRINT 'a'
END
ELSE IF #ConfBy <> ''
AND (
#MonRemark = ''
OR #confstatus = ''
AND (
#StatGD = ''
OR #StatGC = ''
OR #STATGTWO = ''
)
)
BEGIN
PRINT 'b'
END
ELSE IF #confstatus <> ''
AND #MonRemark = ''
AND #ConfBy = ''
AND (
#StatGD = ''
OR #StatGC = ''
OR #STATGTWO = ''
)
BEGIN
PRINT 'c'
END
ELSE IF (
#StatGD <> ''
OR #StatGC <> ''
OR #STATGTWO <> ''
)
AND #confstatus = ''
AND #MonRemark = ''
AND #ConfBy = ''
BEGIN
PRINT 'd'
END
ELSE
BEGIN
PRINT 'e'
END

What's wrong with my IF/ELSE? "ELSE: Incorrect syntax near 'ELSE'."

I have code similar to this:
DECLARE #IdentificationNumber INT
DECLARE #Foreign_ID BIGINT
IF ((SELECT COUNT(*) FROM [main-table] WHERE [identification-number] = #IdentificationNumber) > 0)
SET #Foreign_ID = (SELECT [Foreign_ID] FROM [main-table] WHERE [identification-number] = #IdentificationNumber)
BEGIN
UPDATE [main-table]
SET [column1] = '', [column2] = '', [column3] = ''
WHERE [Foreign_ID] = #Foreign_ID
END
BEGIN
UPDATE [table2]
SET [column4] = '', [column5] = '', [column6] = ''
WHERE [Foreign_ID] = #Foreign_ID
END
BEGIN
UPDATE [table3]
SET [column7] = '', [column8] = '', [column9] = ''
WHERE [Foreign_ID] = #Foreign_ID
END
-- and so on, up to 14
ELSE -- "Incorrect syntax near 'ELSE'.
BEGIN
INSERT into ... -- blah blah blah.
END
...but I get an error while trying to use ELSE: Incorrect syntax near 'ELSE'.
IF - Else syntax is
If condition
begin
--statement
end
else
begin
--statement
end
In your query after First IF statement you bunch of Begin - End statements all those has to be wrapped inside a Begin - End . Like
IF ((SELECT COUNT(*) FROM [main-table] WHERE [identification-number] = #IdentificationNumber) > 0)
Begin -- Missing
SET #Foreign_ID = (SELECT [Foreign_ID] FROM [main-table] WHERE [identification-number] = #IdentificationNumber)
BEGIN
UPDATE [main-table]
SET [column1] = '', [column2] = '', [column3] = ''
WHERE [Foreign_ID] = #Foreign_ID
END
BEGIN
UPDATE [table2]
SET [column4] = '', [column5] = '', [column6] = ''
WHERE [Foreign_ID] = #Foreign_ID
END
BEGIN
UPDATE [table3]
SET [column7] = '', [column8] = '', [column9] = ''
WHERE [Foreign_ID] = #Foreign_ID
END
END -- Missing
else
....

sql server query concat string with '-'

In my SQL query, I'm trying to concatenate two strings in my select clause. Here's the expected results:
col A col B Result
null null &
null '' &
null XYZ XYC
'' null &
'' '' &
'' XYZ XYC
ABC null ABC
ABC '' ABC
ABC XYZ ABC-XYC
My challenge is this - how do I get the 'dash' to show up for the last scenario and not the others?
Here's my attempt:
DECLARE #ColA as varchar(10)
DECLARE #ColB as varchar(10)
set #ColA = null; set #ColB = null; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = null; set #ColB = ''; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = null; set #ColB = 'XYC'; select 'XYC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = ''; set #ColB = null; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = ''; set #ColB = ''; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = ''; set #ColB = 'XYC'; select 'XYC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = 'ABC';set #ColB = null; select 'ABC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = 'ABC';set #ColB = ''; select 'ABC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = 'ABC';set #ColB = 'XYC'; select 'ABC-XYC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
Do you think I have to do one giant case when? I have many columns like this, and that would make it unbearable to read.
Thanks!
UPDATE: if I use a case when, then my select looks like this, which seems to work, but is going to be a pain.
select
case when (#ColA is not null and #ColA <> '') and
(#ColB is not null and #ColB <> '')
then #ColA + '-' + #ColB
else COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&')
end
really hoping someone has some suggestions for improvement!
Could you use a searched case function like this?
Select Case When isnull(ColA, '') + isnull(ColB, '') == '' Then '&'
When isnull(ColA, '') <> '' and isnull(ColB, '') <> '' Then ColA + '-' + ColB
Else isnull(ColA, '') + isnull(ColB, '')
From Table1
I think this answer isn't a whole lot different than one of the other ones, but you might try this:
SELECT
CASE
WHEN NULLIF(ColA,'') <> '' AND NULLIF(ColB,'') <> ''
THEN ColA + '-' + ColB
WHEN NULLIF(ColA,'') <> '' OR NULLIF(ColB,'') <> ''
THEN COALESCE(ColA,ColB)
ELSE '&'
END

Resources