If statement within switch - sql

I know I'm just thinking of the logic all wrong here but how do I achieve the following:
update #table
set column1 = case
when column1 <> ''
then rtrim(column1) + ', ' + rtrim(column2)--if statement here
else rtrim(column2)
end
from #othertable
I basically want to check if rtrim(column 2) = 'value' then replace it with something else. I understand this is within a switch statement, so how would this be acheived?

update #table
set column1 = case
when column1 <> ''
then rtrim(column1) + ', ' +
case
when column2 = 'value'
then rtrim(column2)
else ...
end
else rtrim(column2)
end
from #othertable

Use a REPLACE within your CASE statement
eg: REPLACE(rtrim(column2),'value','newValue');
Refer MSDN for more details on REPLACE

may be you don't need any switch and if clause:
update #table set column1 = rtrim(isnull(nullif(column1,'') + ', ', '')) + rtrim(column2)

Related

How to check if field is NULL and blank?

I'm trying to remove the possibility of blank spaces by a value not existing in the database when creating the view for my lookup. The issue I'm having is that my CASE statement isn't working quite right when I'm trying to check for a NULL or blank value. It seems to work for those that are null but the blank doesn't seem to have as much luck. In this case I am trying to check for null or blank of importantField
CREATE VIEW Lookup4 AS
SELECT TOP 140000 CONCAT(no,
CASE WHEN (importantField is null OR importantField = '')
THEN '' ELSE ' ' + importantField END,
fieldname + ' ', anotherField2) AS UNRELATEDFIELD, Code,
CASE NAME
WHEN '101,,,,,' THEN 'value1e'
WHEN '14,,,,,' THEN 'value3'
WHEN '16,,,,,' THEN 'value4'
END AS NAME
FROM dbo.Lookup
Is this what you are after
CREATE VIEW Lookup4 AS
SELECT TOP 140000 CONCAT(no,
CASE WHEN (ISNULL(importantField,'') = '')
THEN '' ELSE ' ' + importantField END,
fieldname + ' ', anotherField2) AS UNRELATEDFIELD, Code,
CASE NAME
WHEN '101,,,,,' THEN 'value1e'
WHEN '14,,,,,' THEN 'value3'
WHEN '16,,,,,' THEN 'value4'
END AS NAME
FROM dbo.Lookup
If you only want to check for null and not for empty strings then you can also use ifnull as you tried. But that is not suitable for empty strings too.
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1
from tablename
Try to change:
importantField is null
with
IsNull(importantField)
CREATE VIEW Lookup4 AS
SELECT TOP 140000 CONCAT(no,ifnull(importantField,'')<>'',
fieldname + ' ', anotherField2) AS UNRELATEDFIELD, Code,
CASE NAME
WHEN '101,,,,,' THEN 'value1e'
WHEN '14,,,,,' THEN 'value3'
WHEN '16,,,,,' THEN 'value4'
END AS NAME
FROM dbo.Lookup
Minor changes according to your result
Method 1:
Select *
From dbo.Lookup
Where IsNull(importantField, '') = ''
Method 2:
Select *
From dbo.Lookup
Where (importantField is NULL or importantField = '')

And condition in Case Statement IN SQL Server

I have the below sql..#FeeType is a parameter of the stored procedure..I am getting a error when I call the below logic..If I remove the and condition and make the logic just
WHEN ''ItemDesc'' THEN ''Item Description1''
then the logic works fine..Can someone please have a look and let me know what I am doing wrong here.
SELECT #FIELDS = (COALESCE(#FIELDS, '' '','''') + ''<td style='' +
''"border:1px solid black;color:white">'' +
(CASE name
WHEN ''ItemDesc'' and '+ #FeeType +' = ''1'' THEN ''Item Description1''
WHEN ''ItemDesc'' and '+ #FeeType +' = ''2'' THEN ''Item Description2''
WHEN ''Units'' THEN ''Units''
WHEN ''Rate'' THEN ''Rate''
WHEN ''Frequency'' THEN ''Frequency''
WHEN ''Annual'' THEN ''Annual''
WHEN ''BasedOn'' THEN ''Based On'' ELSE ''Misc'' END) + ''</td>''
)
FROM tempdb.sys.Columns
WHERE object_id=object_id(''tempdb..#FeesCalculation'')
AND name not like ''CustColHTML_ID''
AND name not like ''ItemID''
Thanks
Because CASE has two different possible syntaxes:
CASE variable WHEN value1 THEN expression2 WHEN value2 THEN expression2 [...] ELSE expression3 END
CASE WHEN condition1 THEN expression1 ELSE expression2 END
The first one is when you simply need to compare the value. If you need any more complex logic you should probably use the second option. In your case it seems you can use a combination of two of the first syntax.
So, what you need to do is:
SELECT #FIELDS = (COALESCE(#FIELDS, '' '','''') + ''<td style='' +
''"border:1px solid black;color:white">'' +
(CASE name
WHEN ''ItemDesc'' THEN CASE #FeeType WHEN ''1'' THEN ''Item Description1'' WHEN ''2'' THEN ''Item Description2'' END
WHEN ''Units'' THEN ''Units''
WHEN ''Rate'' THEN ''Rate''
WHEN ''Frequency'' THEN ''Frequency''
WHEN ''Annual'' THEN ''Annual''
WHEN ''BasedOn'' THEN ''Based On'' ELSE ''Misc'' END) + ''</td>''
)
You will probably need to fix the concatenation and quotes, I removed them for simplicity.

Printing out list of attribute descriptions based on boolean columns in SQL

I've got a table with a few boolean columns like: IsProductionWorker, IsMaterialHandler, IsShopSupervisor, etc. A record in this table may have several of these column values as true.
What I would like to do is have a query that returns 1 field with a list of all the attributes that are true, say AttributeList which, if those 3 columns were true would return: "Production Worker, Material Handler, Shop Supervisor".
I can think of a few brute force methods and maybe a more elegant method through the use of a temp-table (I've done similar things before), but I'm curious as to what the best way of doing this would be and if there are any easier implementations.
Thanks.
No elegance is possible, really. Simplicity, yes.
Per row you want to change a flag into a string, for each flag. Not many options for cleverness...
SELECT
SUBSTRING (
CASE WHEN IsProductionWorker = 1 THEN ', Production Worker' ELSE '' END +
CASE WHEN IsMaterialHandler= 1 THEN ', Material Handler' ELSE '' END +
CASE WHEN IsShopSupervisor= 1 THEN ', Shop Supervisor' ELSE '' END +
... ,
3, 8000)
FROM
MyTable
WHERE
...
You can try this.
select CASE WHEN isProductionWorker = 1 THEN 'Production Worker' ELSE '' END
+ CASE WHEN cast(isProductionWorker as int) + isMaterialHandler = 2 THEN ', ' else '' END
+ CASE WHEN isMaterialHandler = 1 THEN 'Material Handler' ELSE '' END
+ CASE WHEN cast(isProductionWorker as int) + isMaterialHandler + isShopSupervisor > 1 THEN ', ' else '' END
+ CASE WHEn isShopSupervisor = 1 THEN 'Shop Supervisor' ELSE '' END AS AttributeList
from MyTable

SQL Server Comma Separated value among columns

I want to select columns as comma-separated values by doing something like:
select column1+','+column2+','+column3+','+coulmn4 from someTable
except if any of the columns hold null values i have to skip that column from adding comma
how to do this is SQL Server?
[All columns are of type varchar so no casting needed]
Select
Case When Len(IsNull(Column1),'') > 0 Then Column1 + ',' Else '' End,
Case When Len(IsNull(Column2),'') > 0 Then Column2 + ',' Else '' End,
Case When Len(IsNull(Column3),'') > 0 Then Column3 + ',' Else '' End,
Case When Len(IsNull(Column4),'') > 0 Then Column4 + ',' Else '' End,
Case When Len(IsNull(ColumnN),'') > 0 Then ColumnN + ',' Else '' End
From
SomeTable
try
Test table
create table #testCol (column1 varchar(10), column2 varchar(10),
column3 varchar(10), column4 varchar(10))
insert #testCol values('a', null,null,'b')
insert #testCol values(null,'a',null,'b' )
insert #testCol values(null,'a','Z','b' )
Query
select isnull(column1,'')+ case when column1 is null then '' else ',' end
+ isnull(column2,'')+ case when column2 is null then '' else ',' end
+ isnull(column3,'')+ case when column3 is null then '' else ',' end
+ isnull(column4,'')
from #testCol
Output
a,b
a,b
a,Z,b
Can you export to csv and then strip out all the double commas?
select isnull(column1 + ',', '') + isnull(column2 + ',', '') + isnull(column3 + ',', '') + isnull(coulmn4, '') from someTable

SQL Server 2008: How to find trailing spaces

How can I find all column values in a column which have trailing spaces? For leading spaces it would simply be
select col from table where substring(col,1,1) = ' ';
You can find trailing spaces with LIKE:
SELECT col FROM tbl WHERE col LIKE '% '
SQL Server 2005:
select col from tbl where right(col, 1) = ' '
As a demo:
select
case when right('said Fred', 1) = ' ' then 1 else 0 end as NoTrail,
case when right('said Fred ', 1) = ' ' then 1 else 0 end as WithTrail
returns
NoTrail WithTrail
0 1
This is what worked for me:
select * from table_name where column_name not like RTRIM(column_name)
This will give you all the records that have trailing spaces.
If you want to get the records that have either leading or trailing spaces then you could use this:
select * from table_name where column_name not like LTRIM(RTRIM(column_name))
A very simple method is to use the LEN function.
LEN will trim trailing spaces but not preceeding spaces, so if your LEN() is different from your LEN(REVERSE()) you'll get all rows with trailing spaces:
select col from table where LEN(col) <> LEN(REVERSE(col));
this can also be used to figure out how many spaces you have for more advanced logic.
SELECT * FROM tbl WHERE LEN(col) != DATALENGTH(col)
Should work also.
There's a few different ways to do this...
My favorite option, assuming your intention is to remove any leading and / or trailing spaces, is to execute the following, which will dynamically create the T-SQL to UPDATE all columns with an unwanted space to their trimmed value:
SELECT
'UPDATE [<DatabaseName>].[dbo].['+TABLE_NAME+']
SET ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']))
WHERE ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']));'+CHAR(13)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<TableName>%'
AND DATA_TYPE!='date'
ORDER BY TABLE_NAME,COLUMN_NAME
If you really need to identify them though, try one of these queries:
SELECT *
FROM [database].[schema].[table]
WHERE [col1]!=LTRIM(RTRIM([col1]))
More dynamic SQL:
SELECT 'SELECT ''['+TABLE_NAME+'].['+COLUMN_NAME+']'',*
FROM [<your database name>].[dbo].['+TABLE_NAME+']
WHERE ['+COLUMN_NAME+'] LIKE ''% ''
OR ['+COLUMN_NAME+'] LIKE '' %'';
GO
'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<filter table name as desired>%'
AND DATA_TYPE!='date'
Here's an alternative to find records with leading or trailing whitespace, including tabs etc:
SELECT * FROM tbl WHERE NOT TRIM(col) = col
Try this:
UPDATE Battles
SET name = CASE WHEN (LEN(name+'a')-1)>LEN(RTRIM(name))
THEN REPLICATE(' ', (LEN(name+'a')-1)- LEN(RTRIM(name)))+RTRIM(name)
ELSE name
END
Spaces are ignored in SQL Server so for me even the leading space was not working .
select col from table where substring(col,1,1) = ' '
wont work if there is only one space (' ') or blank ('')
so I devised following:
select * from [table] where substring(REPLACE(col, ' ', '#'),1,1) = '#'
Here is another alternative for trailing spaces.
DECLARE #VALUE VARCHAR(50) = NULL
DECLARE #VALUE VARCHAR(50) = ' '
IF ((#VALUE IS NOT NULL) AND (LTRIM(RTRIM(#VALUE)) != ''))
BEGIN
SELECT 'TRUE'
END
ELSE
BEGIN
SELECT 'FALSE'
END
I have found the accepted answer a little bit slower:
SELECT col FROM tbl WHERE col LIKE '% ';
against this technique:
SELECT col FROM tbl WHERE ASCII(RIGHT([value], 1)) = 32;
The idea is to get the last char, but compare its ASCII code with the ASCII code of space instead only with ' ' (space). If we use only ' ' space, an empty string will yield true:
DECLARE #EmptyString NVARCHAR(12) = '';
SELECT IIF(RIGHT(#EmptyString, 1) = ' ', 1, 0); -- this returns 1
The above is because of the Microsoft's implementation of string comparisons.
So, how fast exactly?
You can try the following code:
CREATE TABLE #DataSource
(
[RowID] INT PRIMARY KEY IDENTITY(1,1)
,[value] NVARCHAR(1024)
);
INSERT INTO #DataSource ([value])
SELECT TOP (1000000) 'text ' + CAST(ROW_NUMBER() OVER(ORDER BY t1.number) AS VARCHAR(12))
FROM master..spt_values t1
CROSS JOIN master..spt_values t2
UPDATE #DataSource
SET [value] = [value] + ' '
WHERE [RowID] = 100000;
SELECT *
FROM #DataSource
WHERE ASCII(RIGHT([value], 1)) = 32;
SELECT *
FROM #DataSource
WHERE [value] LIKE '% ';
On my machine there is around 1 second difference:
I have test it on table with 600k rows, but larger size, and the difference was above 8 seconds. So, how fast exactly will depend on your real case data.
Another way to achieve this by using CHARINDEX and REVERSE like below:
select col1 from table1
WHERE charindex(' ', reverse(col1)) = 1
See example Here
Simple use below query to get values having any number of spaces in begining or at end of values in column.
select * from table_name where column_name like ' %' or column_name like '% ';
We can try underscore to find the entries which are blanks,though not an accurate solution like using '% %' or ' ', But I could find entries which are blanks.
select col_name from table where col_name like '_'