SQL Server concatenation [closed] - sql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
I am trying to concat columns with a comma , as the delimiter.
My concern is that any column with NULL will end up with only a , and if two columns are NULL, I'd get ,,.
How to dynamically find and replace these multiple commatas ,,, to a single ,? Please support

If you are using SQL Server 2017+ just use concat_ws which ignores nulls
Eg
select concat_ws(', ','abc',null,'def')
Result: abc, def

Use CONCAT_WS to concatenate several columns and skip nulls:
select concat_ws(' ', 'hallo', null, 'world', null);
returns 'hello world'.
In your case you want a comma as a separator, hence:
select concat_ws(',', col1, col2, col3, col4) from mytable;
Demo: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=b55f64bd22f5e20e23f156ad23ab85e0

One quick trick is using ISNULL or COALESCE to null check.
If not null concat comma+string, else an empty string.
The ideal solution is STRING_AGG or CONCAT_WS which does like string.Join in C#

Another way :
select concat('hallo' + ', ', null + ', ', 'world' + ', ', null + ', ');

Related

Extract name from a string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 days ago.
Improve this question
Example:
SubNetwork=ONRM_ROOT_MO,SubNetwork=RadioNode,MeContext=BAS917L
I want to extract only RadioNode
SubNetwork=ONRM_ROOT_MO,SubNetwork=GALRNC1,MeContext=BAT045W
I want to extract only GALRNC1.
You can do it using SUBSTRING and LEFT and charindex
select LEFT(sub1, CHARINDEX(',MeContext', sub1) - 1)
from (
select
SUBSTRING(column1, charindex('SubNetwork=', column1, 2) + LEN('SubNetwork='), 20) sub1
from mytable
) as s
charindex to get the position of your word in this case it is SubNetwork=.
SUBSTRING to Extract characters from a string.
LEFT to Extract characters from a string (starting from left).
Demo here
Please try the following solution.
It is using JSON and will work starting from SQL Server 2016 onwards.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (id INT IDENTITY PRIMARY KEY, tokens NVARCHAR(1024));
INSERT #tbl (tokens) VALUES
(N'SubNetwork=ONRM_ROOT_MO,SubNetwork=RadioNode,MeContext=BAS917L'),
(N'SubNetwork=ONRM_ROOT_MO,SubNetwork=GALRNC1,MeContext=BAT045W');
-- DDL and sample data population, end
SELECT t.*
, SubNetwork = JSON_VALUE(j,'$.SubNetwork')
FROM #tbl AS t
CROSS APPLY (SELECT '{"' + REPLACE(REPLACE(STRING_ESCAPE('~'+tokens,'json')
,',','","')
,'=','":"') + '"}'
) AS t1(j);;
Output
id
tokens
SubNetwork
1
SubNetwork=ONRM_ROOT_MO,SubNetwork=RadioNode,MeContext=BAS917L
RadioNode
2
SubNetwork=ONRM_ROOT_MO,SubNetwork=GALRNC1,MeContext=BAT045W
GALRNC1

To compare to column in sql [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have two columns in two different tables.
First column is number like 0493484402 and second column is audit_detail like 'addr_mastersubscription has changed from 32488141893 to 32488141973'.
I have to check whether first column value is present or not in second column's entire string.
If the number is not present I need that number as output
You could use LIKE here:
SELECT *
FROM table1 t1
INNER JOIN table2 t2
ON t2.audit_detail LIKE '%' || t1.col1 || '%';
We can also use INSTR:
SELECT *
FROM table1 t1
INNER JOIN table2 t2
ON INSTR(t2.audit_detail, t1.col1) > 0;
I think, with solution of like and instr, you must have some delimeter which comes before and after your string in second column. Else 1 as a fisrt column will match eith 123 in second column.
Looking at the sample data, you can use space as a delimeter. But you will need leading and trailing space compulsory in your second column for matching first column.
You can use something like this:
Select *
Table1 t1 join table2 t2
On ' ' || t2.second_column || ' ' like '% ' || t1.first_column || ' %';

Append “tail” to multiple selects [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have multiple result rows that has following structure
select data0, data1, ..., data30 from t0
union all select data0, ..., data30 from t1
...
There are multiple result rows, many of which need
to be aligned to the length of 30. So me do following
union all select data0, data1, null, null, ..., null
Is there a convenient way to automate this kind of
task. What I want is to append tail nulls as needed.
What I do now
with nulls as (
select null as nul0, ..., null as nul30 from dual
)
And I am stuck at this point. How to append this nulls to
result rows? Number of empty columns are known.
Pls edit as appropriate, I type from mobile
How to append this nulls to result rows?
There is no built-in solution for generating a projection of an arbitrary number of columns.
This solution will take a fair amount of typing but you can semi-automate it by using a text editor which supports regex search'n'replace patterns.
with nulls as (
select cast(null as varchar2(10)) as nul0
, ...
, cast(null as varchar2(10)) as nul30
from dual
)
select t1.dat01
, t1.dat02
, nulls.nul03 as dat03
, nulls.nul04 as dat04
...
, nulls.nul30 as dat30
from t1
cross join nulls
union all
select t2.dat01
, t2.dat02
, t2.dat03
, nulls.nul04 as dat04
...
, nulls.nul30 as dat30
from t2
cross join nulls

Convert multiple rows into one with coma as separator [duplicate]

This question already has answers here:
How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field? [duplicate]
(13 answers)
Closed 7 years ago.
If I issue SELECT ID FROM TestAhmet I get this result:
1
3
5
2
4
but what I really need is one row with all the values separated by comma, like this:
1,2,3,4,5
How do I do this?
ps: I cant do this : Convert multiple rows into one with comma as separator
If id is numeric column then do like this
select stuff((select ',' +Convert(varchar(50),id)
from TestAhmet
for xml path ('')
), 1, 1, '') as users
This should work:
select stuff((select ',' + cast(id as varchar(8000))
from TestAhmet
for xml path ('')
), 1, 1, '') as users
This is a variation on the string aggregation logic often used in SQL Server. But, without a group by, you probably won't find many examples on the web.

Empty value in a IN clause with select query [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to use empty value in an IN clause. But following queries don't work identically.
SELECT * from tblTest WHERE colName IN ( '')
SELECT * from tblTest WHERE colName IN (SELECT '''''')
The first works fine but the second has no error but gives empty result.
It's because SELECT '''''' will return you '' and try to compare your values to it, which is not an empty string.
Anyway, it's not quite clear what you're trying to achieve.
That's pretty clear: you want the rows where the column contains an empty string. But if you compare with (select '''''') you dont select an empty string! You select a string that looks like this: ''
This works:
SELECT * from tblTest WHERE colName IN (SELECT '')