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
Related
I need to remove all the empty column for a given table.
As it could by any table, I do not know the name of the columns.
For example, the input table is table1 :
Id
Value1
Value2
Value3
Value4
1
Cell 2
NULL
Cell 2
NULL
2
Cell 4
NULL
Cell 4
NULL
The output table should be :
Id
Value1
Value3
1
Cell 2
Cell 2
2
Cell 4
Cell 4
You can try that.
set #sql = null;
select concat_ws(', ',
case when count(nullif(ID, '')) > 0 then 'ID' end,
case when count(nullif(Value1, '')) > 0 then 'Value1' end,
case when count(nullif(Value2, '')) > 0 then 'Value2' end,
case when count(nullif(Value3, '')) > 0 then 'Value3' end,
case when count(nullif(Value4, '')) > 0 then 'Value4' end
) into #sql
from table1 ;
set #sql = concat('select ', #sql, ' from imported_data where',
(
SELECT INSERT( GROUP_CONCAT('OR `', `COLUMN_NAME`, '` != \'\' ' SEPARATOR ' '), 1, 3, '')
FROM `information_schema`.`COLUMNS`
WHERE `TABLE_SCHEMA` = 'mydb'
AND `TABLE_NAME` = 'table1'
)
);
prepare stmt from #sql;
execute stmt;
deallocate prepare stmt;
The nullif clause checks if there are any strictly empty fields, if you want to include null values you will have to remove the nullif.
DECLARE #mockup TABLE(Column1 VARCHAR(1),Column2 VARCHAR(1));
INSERT INTO #mockup VALUES('1','2'),('-','2'),('1','2'),('-','-'),('2','-'),('1','2');
SELECT ISNULL(NULLIF(Column1 + '|','-|'),'')
+ISNULL(NULLIF(Column2,'-'),'')
FROM #mockup
Above query result is as below,
1|2
2
1|2
2|
1|2
I want the result as above only except row4, where 2| should be only as 2 .
'|' should not be there at before or end of the values.
Simply join both fields and use REPLACE to remove |- and -|. Condition in WHERE clause avoids records where both fields are -:
select replace(replace(Column1+'|'+Column2,'-|',''),'|-','') as Result
from mockup
where coalesce(nullif(Column1,'-'),nullif(Column2,'-')) is not null
Output:
Result
1|2
2
1|2
2
1|2
See result here.
Use Replace function
SELECT replace(replace(replace(Column1 + '|' + Column2,'-|',''),'|-',''),'-','')
FROM #mockup
or try using CASE statement
SELECT CASE
WHEN column1 LIKE '[0-9]' AND column2 LIKE '[0-9]' THEN column1 + '|' + column1
WHEN column1 LIKE '[0-9]' AND column2 NOT LIKE '[0-9]' THEN column1
ELSE column2
END
FROM #mockup
if you want to check the - instead of numbers then
SELECT CASE
WHEN column1 NOT LIKE '-' AND column2 NOT LIKE '-' THEN column1 + '|' + column1
WHEN column1 NOT LIKE '-' AND column2 LIKE '-' THEN column1
ELSE column2
END
FROM #mockup
I would do this as:
select stuff( ((case when column1 not like '-' then '|' + column1 else '' end) +
(case when column2 not like '-' then '|' + column2 else '' end)
), 1, 1, '');
This is the simplest way that I've found to implement concat_ws() in SQL Server. concat_ws() is a function available in other databases, where you would just do:
select concat_ws('|',
(case when column1 not like '-' then column1 end),
(case when column2 not like '-' then column2 end)
)
I combine two column value with ',' using below query.
SELECT
RTRIM(LTRIM(REPLACE(
IsNull(tbl1 .Reason,'') + ',' + IsNull(tbl2.OtherReason,''),',' ,'')))
FROM tbl1
LEFT JOIN tbl2 ON tbl2.OtherReasonId = tbl1.ReasonId
Now issue is that it remove all ',' using above query and I want to just remove last and first ','.
I have combine two column. Now
if tbl1 .Reason is null then it display output as " ,tbl2.OtherReason " and if tbl2.OtherReason is null the output is "tbl1 .Reason,"
Before above query, I also try with below query:
SELECT
IsNull(tbl1.Reason,'') + ',' + IsNull(tbl2.OtherReason,'')
FROM tbl1
LEFT JOIN tbl2 ON tbl2.OtherReasonId = tbl1.ReasonId
Thanks,
HItesh
You can use a case in the middle to check if the values are null or not.
declare #a nvarchar(5)
,#b nvarchar(5)
set #a = 'abc'
set #b = null--'123'
select isnull(#a, '') + case when #a is not null and #b is not null then ',' else '' end + isnull(#b, '')
Try this:
SELECT
CASE
WHEN tbl1.Reason IS NULL
THEN
CASE
WHEN tbl2.Reason IS NULL
THEN ''
ELSE LTRIM(RTRIM(tb2.Reason))
END
ELSE tbl1.Reason +
CASE
WHEN tbl2.Reason IS NULL
THEN ''
ELSE ',' + LTRIM(RTRIM(tb2.Reason))
END
END
FROM tbl1
LEFT JOIN tbl2 ON tbl2.OtherReasonId = tbl1.ReasonId
You can concatenate a comma to the first value in case that second value is not null :
SELECT
IsNull(tbl1.Reason + case when tbl2.OtherReason is null then '' else ',' end, '') +
IsNull(tbl2.OtherReason,'')
FROM tbl1
LEFT JOIN tbl2 ON tbl2.OtherReasonId = tbl1.ReasonId
I am trying to combine multiple columns (varchar, but used to store boolean 'Y' or '') into a single column (list) with human readable text.
The Table layout is like this:
MEMBER_ID (int) | PROC (varchar) | 50K_12_MTHS (varchar) | 100K_12_MTHS (varchar)
1||||
2|Y|Y||
3|Y|Y|Y|
4|Y|||
For the output of the able sample I am trying to get:
1|
2|Proc, 50
3|Proc, 50, 100
4|Proc
I think the way to do this is with a Case (see below) but can't get it to work.
SELECT
MEMBER_ID,
Gorup =
Select(
CASE PROC
WHEN 'Y'
THEN 'Proc'
END + ', ' +
CASE 50K_12_MTHS
WHEN 'Y'
THEN '50K'
END-- + ', ' +
CASE 100K_12_MTHS
WHEN 'Y'
THEN '100K'
END + ', ' +)
from Members
Nearly...!
SELECT
MEMBER_ID,
CASE [PROC]
WHEN 'Y' THEN 'Proc, '
ELSE ''
END +
CASE [50K_12_MTHS]
WHEN 'Y' THEN '50K,'
ELSE ''
END +
CASE [100K_12_MTH]
WHEN 'Y' THEN '100K, '
ELSE ''
END as [group]
from Members
Try this
SELECT
MEMBER_ID,
(CASE [PROC] WHEN 'Y'
THEN 'Proc' ELSE ''
END +
CASE [50K_12_MTHS] WHEN 'Y'
THEN ', 50K' ELSE '' END
+ CASE [100K_12_MTHS] WHEN 'Y'
THEN ', 100K' ELSE ''
END) as [GROUP]
from Members
I use the following SQL to concatenate several database columns from one table into one column in the result set:
SELECT (field1 + '' + field2 + '' + field3) FROM table1
When one of the fields is null I got null result for the whole concatenation expression. How can I overcome this?
The database is MS SQL Server 2008. By the way, is this the best way to concatenate database columns? Is there any standard SQL doing this?
The SQL standard way of doing this would be:
SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1
Example:
INSERT INTO table1 VALUES ('hello', null, 'world');
SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1;
helloworld
If you were using SQL 2012 or above you could use the CONCAT function:
SELECT CONCAT(field1, field2, field3) FROM table1
NULL fields won't break your concatenation.
#bummi - Thanks for the comment - edited my answer to correspond to it.
Normal behaviour with NULL is that any operation including a NULL yields a NULL...
- 9 * NULL = NULL
- NULL + '' = NULL
- etc
To overcome this use ISNULL or COALESCE to replace any instances of NULL with something else..
SELECT (ISNULL(field1,'') + '' + ISNULL(field2,'') + '' + ISNULL(field3,'')) FROM table1
If you are having a problem with NULL values, use the COALESCE function to replace the NULL with the value of your choice. Your query would then look like this:
SELECT (COALESCE(field1, '') + '' + COALESCE(field2, '') + '' + COALESCE(field3,'')) FROM table1
http://www.codeproject.com/KB/database/DataCrunching.aspx
Use ISNULL to overcome it.
Example:
SELECT (ISNULL(field1, '') + '' + ISNULL(field2, '')+ '' + ISNULL(field3, '')) FROM table1
This will then replace your NULL content with an empty string which will preserve the concatentation operation from evaluating as an overall NULL result.
If both Column are numeric Then Use This code
Just Cast Column As Varchar(Size)
Example:
Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table
Just Cast Column As Varchar(Size)
If both Column are numeric then use code below.
Example:
Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table
What will be the size of col3 it will be 40 or something else