sybase sql column concatenation conditionally - sql

Please help me in concatenation the columns,
Col1 Col2 col3
a b c
a3 null null
Expected output is :
col1:a col2:b col3:c
col1:a3
expected is Do not include null column name and value both.
Thanks in advance...

Here is one method:
select stuff( coalesce('col1:' + col1, ' ') +
coalesce('col2:' + col2, ' ') +
coalesce('col3:' + col3, ' '),
1, 1, ''
) as concatted_values

Related

Concatenate SQL columns with comma separated

Is there any alternate way to concatenate SQL columns with comma separated. I am using below logic for concatenation. The columns (col1,col2,col3) can have null values.
select
stuff(
left(concat(col1,',',col2,',',col3),
len(concat(col1,',',col2,',',col3)) -
patindex('%[^,]%',reverse(concat(col1,',',col2,',',col3)))+1
)
,1,
patindex('%[^,]%',concat(col1,',',col2,',',col3))-1,''
)
from mytable
Sample data/output
In more recent versions of SQL Server you can use concat_ws():
select concat_ws(',', col1, col2, col3)
In earlier versions, there are various approach. A pretty simple one is:
select stuff( concat(',' + col1, ',' + col2, ',' + col3), 1, 1, '')
You can concat separators conditionally. This will output an empty string if either of the columns are null or empty.
select concat(col1,
case when len(col2)>1 then ',' else '' end,
col2,
case when len(col3)>1 then ',' else '' end,
col3)
from your_table;
To output null if either of the columns are null or empty, wrap the concat inside a nullif like this
select nullif(concat(col1,
case when len(col2)>1 then ',' else '' end,
col2,
case when len(col3)>1 then ',' else '' end,
col3),'')
from your_table;

Exclude Null Entries when concatenate

I have columns
Col1|Col2|Col3
Aaaa|Bbbb|Cccc
Null|Bbbb|Cccc
Aaaa|Bbbb|Null
My result should look like
Aaaa,Bbbb,Cccc
Bbbb,Cccc
Aaaa,Bbbb
I tried this with the common '+' way of concatenation like
Select Col1 + ', ' + Col2 + ', ' + Col3
but with this statement I do get Nulls in the resultset if there is a Null in one of the columns. I could do something like
ISNULL(Col1, ' ')
but this end up in having ',' signs messing around
Can anyone help me out here?
The CONCAT() function solves your problem:
Select CONCAT(Col1, ', ', Col2, ', ', Col3)
It ignores NULL values.
The most recent versions of SQL Server support CONCAT_WS():
CONCAT_WS(', ', col1, col2, col3)
This produces slightly different results. For instance, if the second two values are NULL, the first returns 'A,,' but the second returns 'A'. I'm not sure which you really want.

MSSQL select lowest but not NULL/zero value from 25 columns

I have 25 (numeric) columns in one table in MSSQL and I need select lowest value, but not NULL or 0 value.
Columns are named like "%_price" (aaa_price, bbb_price, ccc_price...).
Some columns contains 0 or NULL value.
Example:
table (aaa_price, bbb_price, ccc_price, ddd_price, eee_price, fff_price)
value (NULL, 0, 324.23, 162.50, NULL, 1729.72 )
Right result:
162.50
I can use some "brute force" method like:
SELECT CASE
WHEN Col1 <= Col2 AND Col1 <= Col3 AND Col1 <= Col4 AND Col1 <= Col5 THEN Col1
WHEN Col2 <= Col3 AND Col2 <= Col4 AND Col2 <= Col5 THEN Col2
WHEN Col3 <= Col4 AND Col3 <= Col5 THEN Col3
WHEN Col4 <= Col5 THEN Col4
ELSE Col5
END AS [Min Value] FROM [Your Table]
But its insane with 25 columns... is there any better solution?
Thank You!
Cross apply can be good option in this case:
select
*
from
myTable
cross apply (select
minVal = min(val)
from (
values (aaa_price),(bbb_price),(...)
) t(val) where val > 0
) q
Edit:
You have to use dynamic SQL if you want to get column names from INFORMATION_SCHEMA.COLUMNS table.
declare #sql varchar(8000)
declare #cols varchar(8000)
select #cols =
stuff((
SELECT
',(' + COLUMN_NAME + ')'
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = 'mytable'
AND TABLE_SCHEMA='dbo'
AND COLUMN_NAME LIKE '%price'
for xml path('')
), 1, 1, '')
set #sql = 'select
*
from
mytable
cross apply (select
minVal = min(val)
from (
values ' + #cols + '
) t(val) where val > 0
) q'
exec (#sql)
You can create a dynamic SQL statement and execute it in the following form
declare #tablename sysname = 'MultipleNumericColumns'
declare #sql nvarchar(max)
select #sql = isnull(#sql + ' union all ','') + '
SELECT ' + name + ' as colname from ' + #tablename
from sys.all_columns
where
object_id = OBJECT_ID(#tablename)
set #sql = '
select min(colname)
from (
' + #sql + '
) t
where colname > 0'
EXECUTE(#sql)
You can realize that first I get the column names from system view
You can exclude columns that you don't want or use a pattern like name like '%price% etc at this step
Then I build a dynamic SQL query into a string variable as sql command
Please note that I use WHERE clause for greater than 0, etc
Final step is execution with EXECUTE command
Use UNPIVOT
SELECT Min(VALUE)
FROM (
SELECT Col1, Col2, Col3...
FROM YourTable
) t
UNPIVOT (VALUE FOR ITEM IN (Col1, Col2, Col3...)) u
WHERE VALUE != 0

How to remove space from SQL

Example
col1 col 2 col3
300 Broad ST
,(IsNUll((Cast(FLOOR(col1) as CHAR (7) )),'') + ' ' + IsNull(col2,'') + ' ' + isnull(col3,'')) as col4
result i get is
300 Broad ST
what i want is
300 Broad St.
there is 4 or 5 space between 300 and Broad
the data type for col1 is numeric and for col 2 and 3 is nvarchar. I don't want to change the data type.
This looks a lot like SQL Server. If so:
stuff(coalesce(' ' + Cast(floor(col1) as varchar(7)), '') +
coalesce(' ' + col2, '') +
coalesce(' ' + col3, ''),
1, 1, '') as col4

concatenate two database columns into one resultset column

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