concatenate values of one column to single text - sql

my Column is like this:
col1
Mary
Jack
John
and i need to get something like this:
Mary,Jack,John
I did it by using "For XML PATH", but the problem is that segment not work in SQL server view,
is there other way to get concatenation of one column?

try using SQL COALESCE experession to convert your column values into a comma separated string.
here's what you need to do.
DECLARE #test TABLE (
SampleCol varchar(50)
)
INSERT INTO #Test
VALUES ('Test')
INSERT INTO #Test
VALUES ('Test 1')
INSERT INTO #Test
VALUES ('Test 2')
INSERT INTO #Test
VALUES ('Test 3')
INSERT INTO #Test
VALUES ('Test 4')
DECLARE #aa varchar(200)
SET #aa = ''
SELECT
#aa =
COALESCE(CASE
WHEN #aa = '' THEN SampleCol
ELSE #aa + ',' + SampleCol
END
, '')
FROM #test
SELECT
#aa
here's a complete SQLFIDDLE

Try this:
DECLARE #tbl TABLE(col1 VARCHAR(10));
INSERT INTO #tbl VALUES('Mary'),('Jack'),('John');
SELECT
STUFF
(
(
SELECT ', ' + col1
FROM #tbl
FOR XML PATH('')
)
,1,2,'')

Related

SQL output of dynamic queries should be in csv

Referring to the code in one of the links found in the internet - that executes sql command stored in DB column
I was trying to get similar output in the form of csv - like query and data along with headers in one result.
Like if we have this data in sql server 2014
CREATE TABLE Table1 (empid INT,
name VARCHAR(1000),
sal INT,
DOB DATETIME,
OrgID INT);
CREATE TABLE Table2 (OrgID INT,
Orgname VARCHAR(1000));
CREATE TABLE Table3 (dummy INT);
INSERT INTO Table1
VALUES (100, 'tst', '10000', '1990-11-20', 1);
INSERT INTO Table1
VALUES (101, 'tst', '10000', '1990-11-20', 1);
INSERT INTO Table1
VALUES (102, 'tst', '10000', '1990-11-20', 2);
INSERT INTO Table2
VALUES (1, 'org1');
INSERT INTO Table2
VALUES (2, 'org2');
CREATE TABLE #List (Command VARCHAR(MAX),
OrderBy INT IDENTITY(1, 1));
INSERT INTO #List
VALUES ('SELECT * FROM Table1'),
('SELECT * FROM Table2'),
('SELECT * FROM Table3');
DECLARE #sqlcmd VARCHAR(MAX);
SELECT #sqlcmd = STUFF(
(SELECT ';' + CHAR(10) + Command + CHAR(10)FROM #List ORDER BY [OrderBy] FOR XML PATH('')), 1, 1, '');
EXEC (#sqlcmd);
Now when i execute the sql's in #List, the output should result with comma seperated.
As they are no records in table3, it should not output in final result.
Am expected the the result all in one column seperated by comma - screenshot attached.
OUTPUT
SELECT FROM Table1, empid,name,sal,DOB,OrgID
SELECT FROM Table1, 100,tst,10000,1990-11-20 00:00:00.000,1
SELECT FROM Table1, 101,tst,10000,1990-11-20 00:00:00.000,1
SELECT FROM Table1, 102,tst,10000,1990-11-20 00:00:00.000,2
select from Table2,OrgID, Orgname
select from Table2,1,org1
select * from Table2,2,org2

How to select from string array added in SQL column?

Below is my table,
create table t(
id int,
colParam varchar(max))
insert into t values(1,'["param1", "param2"]')
insert into t values(2,'["param2"]')
insert into t values(3,'["param1"]')
insert into t values(4,'["param2", "param3"]')
insert into t values(5,'["param1", "param2"]')
tried
declare #str varchar(max) = 'param1'; Select * from t where colParam like '%'+ #str+'%'
its not working for
declare #str varchar(max) = 'param1,param2'; Select * from t where colParam like '%'+ #str+'%'
i want to select rows by passing colPar as 'param1,param2' so it will result me all the records containing param1 and param2 in colParam
This quiet tricky.
create table #t(
id int,
colParam varchar(max)
)
insert into #t values(1,'["param1", "param2"]')
insert into #t values(2,'["param2"]')
insert into #t values(3,'["param1"]')
insert into #t values(4,'["param2", "param3"]')
insert into #t values(5,'["param1", "param2"]')
declare #str varchar(max) = 'param1,param2';
to Return all matching values.
select distinct id, t1.colParam from #t t1
cross apply string_split(t1.colParam, ',') t2
cross apply string_split(#str, ',') t3
where t2.value like '%'+t3.value+'%'
Output:
If you are using SQL Server 2016 and above, then you can use STRING_SPLIT.
As MSDN says:
A table-valued function that splits a string into rows of substrings,
based on a specified separator character.
So your can look like this:
DECLARE #t TABLE
(
id int,
colParam varchar(max)
)
insert into #t values(1,'["param1", "param2"]')
insert into #t values(2,'["param2"]')
insert into #t values(3,'["param1"]')
insert into #t values(4,'["param2", "param3"]')
insert into #t values(5,'["param1", "param2"]')
SELECT
t.id
, s.col
FROM #t AS t
OUTER APPLY
(
SELECT
spl.value AS col
FROM STRING_SPLIT(
(SELECT _t.colParam FROM #t AS _t WHERE _t.id = t.id), ',') AS spl
)s

Sql Query to display output horizontally

I need to display a query output in a horizontal manner. I have some example data
create table TestTable (id number, name varchar2(10))
insert into TestTable values (1, 'John')
insert into TestTable values (2, 'Mckensy')
insert into TestTable values (3, 'Valneech')
insert into TestTable values (4, 'Zeebra')
select * from TestTable
This gets the output in a vertical view.
ID Name
==========
1 John
2 Mckensy
3 Valneech
4 Zeebra
However, I need to display it horizontally.
ID 1 2 3 4
Name John Mckensy Valneech Zeebra
create table #TestTable (id int, name varchar(10))
insert into #TestTable values (1, 'John')
insert into #TestTable values (2, 'Mckensy')
insert into #TestTable values (3, 'Valneech')
insert into #TestTable values (4, 'Zeebra')
select *
from
(
select *
from #TestTable
) src
pivot
(
max(name)
for id in ([1], [2], [3],[4])
) piv;
output
1 2 3 4
John Mckensy Valneech Zeebra
You can also use dynamic sql query something like below.
Query
declare #sql as varchar(max);
select #sql = 'select ' + char(39) + 'Name' + char(39) + ' Id,' + stuff((
select
',max(case [Id] when ' + cast(id as varchar(10)) + ' then name end) ['
+ cast([Id] as varchar(10)) + ']'
from TestTable
for xml path('')
), 1, 1, '');
select #sql += 'from TestTable;';
exec(#sql);

SQL - advice on grouping

SQL Server 2005. I am not after a coded answer here (although it would be nice). I'm really after advice on the best way forward to get the result I need. I have some knowledge of pivot/unpivot/cte//rownumber and dynamic queries but cannot get my head around this particular problem! An example of the data follows. Note: The occurrence of type,location,name and description can be none to many.
drop table #temp
create table #temp
(
event int,
type varchar(20),
locations varchar(20),
name varchar(30),
description varchar(50)
)
insert into #temp values (1,'support','r1','fred','desc 1')
insert into #temp values (1,'support','r1','fred','desc 2')
insert into #temp values (1,'support','r1','fred','desc 3')
insert into #temp values (1,'support','r1','jim','desc 1')
insert into #temp values (1,'support','r1','jim','desc 2')
insert into #temp values (1,'support','r1','jim','desc 3')
insert into #temp values (1,'support','r2','fred','desc 1')
insert into #temp values (1,'support','r2','fred','desc 2')
insert into #temp values (1,'support','r2','fred','desc 3')
insert into #temp values (1,'support','r2','jim','desc 1')
insert into #temp values (1,'support','r2','jim','desc 2')
insert into #temp values (1,'support','r2','jim','desc 3')
insert into #temp values (1,'work','r1','fred','desc 1')
insert into #temp values (1,'work','r1','fred','desc 2')
insert into #temp values (1,'work','r1','fred','desc 3')
insert into #temp values (1,'work','r1','jim','desc 1')
insert into #temp values (1,'work','r1','jim','desc 2')
insert into #temp values (1,'work','r1','jim','desc 3')
insert into #temp values (1,'work','r2','fred','desc 1')
insert into #temp values (1,'work','r2','fred','desc 2')
insert into #temp values (1,'work','r2','fred','desc 3')
insert into #temp values (1,'work','r2','jim','desc 1')
insert into #temp values (1,'work','r2','jim','desc 2')
insert into #temp values (1,'work','r2','jim','desc 3')
select * from #temp
The result I am after is this ..
1,support;work,r1;r2,fred;jim,desc1;desc2;desc3
Your goal seem to select all distinct value of all columns, then Concatenate into one string. And you only need advice, so I recommend you go here: multiple rows into a single row
It seem that you need more help:
select distinct
stuff((SELECT distinct'; ' + type-- as type
FROM #temp
--order by type
FOR XML PATH('')),1,1,'')
+ (SELECT distinct'; ' + locations
FROM #temp
FOR XML PATH(''))
+ (SELECT distinct'; ' + name
FROM #temp
FOR XML PATH(''))
+ (SELECT distinct'; ' + description
FROM #temp
FOR XML PATH(''))
from #temp;
If you need 4 columns, then change + (SELECT to , stuff((SELECT
The query is just that simple: get distinct of one column, change into string, then concatenate + string of (next column)...
This is slightly unrelated, but when inserting data like this it would be easier (for you) to do it like this (also, try to get into the habit of naming the fields you are inserting into);
INSERT INTO #temp (event, type, locations, name, description)
VALUES (1,'support','r1','fred','desc 1')
,(1,'support','r1','fred','desc 2')
,(1,'support','r1','fred','desc 3')
,(1,'support','r1','jim','desc 1')
,(1,'support','r1','jim','desc 2')
Please don't up-vote this version! All up-votes should go to the solution above! The code below is simply for completeness. This shows the syntax for organising the data into separate columns based on the answer from #NayruLove
SELECT distinct x.event,
stuff((SELECT distinct'; ' + t.type
FROM #temp t
where t.event = x.event
FOR XML PATH('')),1,1,'') as type
, stuff((SELECT distinct'; ' + locations
FROM #temp t
where t.event= x.event
FOR XML PATH('')),1,1,'') as room
, stuff((SELECT distinct'; ' + name
FROM #temp t
where t.event = x.event
FOR XML PATH('')),1,1,'') as name
, stuff((SELECT distinct'; ' + description
FROM #temp t
where t.event = x.event
FOR XML PATH('')),1,1,'') as description
from #temp x
group by x.event

SQL Substring on varying column

I have a database table with a column METADATA. This METADATA may or may not contain a string. Here's the sample string:
StudentID:1234,StudentName:TestName,StudentNickName:TestNName,StudentLevel:5
Now, I want to extract the StudentNickName:TestName if it exists. Please note of the following constraint:
METADATA column doesn't always contain a value
METADATA column can contain a value without the StudentNickName clause
The StudentNickName: is fixed, while the TestNName varies per row.
For mssql 2005+
declare #t table(metadata varchar(200))
insert #t values('StudentID:1234,StudentName:TestName,StudentNickName:TestNName,StudentLevel:5')
insert #t values('')
insert #t values('StudentID:1234,StudentName:Thomas,StudentNickName:Tom,StudentLevel:3')
select left(b.a, patindex('%_,%', b.a)) StudentNickName
from #t t cross apply
(select right(metadata, patindex('%_:emaNkciNtnedutS%'
, reverse('X'+ metadata)))+',' a) b
Result:
StudentNickName
---------------
TestNName
Tom
Works in Sql Server
DECLARE #test TABLE(metadata VARCHAR(200))
INSERT #test VALUES('StudentID:1234,StudentName:TestName,StudentNickName:TestNName,StudentLevel:5')
INSERT #test VALUES('StudentID:1235,StudentName:TestName1,StudentNickName:TestNName1,StudentLevel:6')
INSERT #test VALUES('StudentID:1236,StudentName:TestName2,StudentNickName:TestNName2,StudentLevel:2')
INSERT #test VALUES('')
SELECT split.s.value('.','VARCHAR(100)') as colname FROM
(
SELECT CAST('<s>' + REPLACE(metadata,',','</s><s>') + '</s>' AS XML) col FROM #test
) AS t CROSS APPLY col.nodes('/s') AS split(s)
WHERE split.s.value('.','VARCHAR(100)') LIKE '%StudentNickName%'