split the accounid and dbids between braces into two columns - sql

I have a query to split the accounid and dbids between braces separately.
example: [14801].[42]
acid scid
14801 42
but I'm not able to separate after comma ,
example :
[27784].[41],[27781].[41],[27779].[41]
need a query to split this data into rows

you need to create function to split values into rows
create function [dbo].[udf_splitstring] (#tokens varchar(max),
#delimiter varchar(5))
returns #split table (
token varchar(200) not null )
as
begin
declare #list xml
select #list = cast('<a>'
+ replace(#tokens, #delimiter, '</a><a>')
+ '</a>' as xml)
insert into #split
(token)
select ltrim(t.value('.', 'varchar(200)')) as data
from #list.nodes('/a') as x(t)
return
end
select * from into #a udf_splitstring ('[27784].[41],[27781].[41],[27779].[41]',',')
output
[27784].[41]
[27781].[41]
[27779].[41]
coming result store in one temp table
SELECT TOKEN,REPLACE(REPLACE(SUBSTRING(TOKEN,0,CHARINDEX('.',TOKEN)),'[',''),']','') AS first_id
,REPLACE(REPLACE(REVERSE(SUBSTRING(REVERSE(TOKEN),0,CHARINDEX('.',REVERSE(TOKEN)))),'[',''),']','') AS second_id
FROM #a
output
TOKEN first_id second_id
[27784].[41] 27784 41
[27781].[41] 27781 41
[27779].[41] 27779 41

Try this:
DECLARE #START_ID VARCHAR(100)='[27784].[41],[27781].[41],[27779].[41]'
DECLARE #ID VARCHAR(MAX)
DECLARE #COUNT INT
DECLARE #TEMP TABLE(C1 VARCHAR(MAX))
WHILE( CHARINDEX(',',#START_ID))>0
BEGIN
INSERT INTO #TEMP SELECT SUBSTRING(#START_ID,0,CHARINDEX(',',#START_ID))
SET #START_ID=(SELECT REPLACE(#START_ID,(SUBSTRING(#START_ID,0,CHARINDEX(',',#START_ID)+1)),''))
END
INSERT INTO #TEMP SELECT #START_ID
SELECT C1,REPLACE(REPLACE(SUBSTRING(C1,0,CHARINDEX('.',C1)),'[',''),']','') AS SOURCE_ACCOUT_ID
,REPLACE(REPLACE(REVERSE(SUBSTRING(REVERSE(C1),0,CHARINDEX('.',REVERSE(C1)))),'[',''),']','') AS SOURCE_DATABASE_ID
FROM #TEMP

select n.ids.value ('id[1]','int') as accountid
,n.ids.value ('id[2]','int') as dbid
from (select cast (replace('<r><e><id>'+replace(replace(replace(
ids,'[',''),']',''),',','</id></e><e><id>')+
'</id></e></r>','.','</id><id>') as xml) as x
from mytable
) t
cross apply x.nodes ('/r/e') n(ids)
+-----------+------+
| accountid | dbid |
+-----------+------+
| 27784 | 41 |
+-----------+------+
| 27781 | 41 |
+-----------+------+
| 27779 | 41 |
+-----------+------+
| 28021 | 30 |
+-----------+------+
| 28024 | 30 |
+-----------+------+
| 29007 | 56 |
+-----------+------+
DDL + DML for demo
create table mytable (ids varchar(1000))
insert into mytable values
('[27784].[41],[27781].[41],[27779].[41]')
, ('[28021].[30],[28024].[30]')
, ('[29007].[56]')

Related

Convert and merge two string as a table

Assume we have two below strings:
DECLARE #AllowedCardBoardIds NVARCHAR(MAX) = '1,2,3,4,5,6'
DECLARE #AllowedCardBoardIdsAccessTypes NVARCHAR(MAX) = '11,22,33,44,55,66'
Also, assume we have a function to split a string as a table.
It returns a sequence values
Select * FROM dbo.SplitString(',', #AllowedCardBoardIds)
-- result:
Value
------
1
2
3
4
5
6
Now I want to convert two string to table and merge them as follows:
Id | AccessType
--------------------
1 | 11
2 | 22
3 | 33
4 | 44
5 | 55
6 | 66
How should I do it?
I wrote a query as follows:
DECLARE #AllowedCardBoardsTable TABLE(
Id INT NOT NULL,
AccessType INT NOT NULL
)
INSERT INTO #AllowedCardBoardsTable
(
Id, AccessType
)
SELECT id.[Value], accessType.[Value]
FROM dbo.SplitString(',', #AllowedCardBoardIds) AS id
But I don't know how to fill AccessType column !
Please try the following solution.
SQL
DECLARE #AllowedCardBoardsTable TABLE(
Id INT NOT NULL,
AccessType INT NOT NULL
);
DECLARE #AllowedCardBoardIds NVARCHAR(MAX) = '1,2,3,4,5,6';
DECLARE #AllowedCardBoardIdsAccessTypes NVARCHAR(MAX) = '11,22,33,44,55,66';
DECLARE #separator CHAR(1) = ',';
;WITH rs AS
(
SELECT CardBoardIds = CAST('<root><r><![CDATA[' +
REPLACE(#AllowedCardBoardIds, #separator, ']]></r><r><![CDATA[') +
']]></r></root>' AS XML)
, CardBoardIdsAccessTypes = CAST('<root><r><![CDATA[' +
REPLACE(#AllowedCardBoardIdsAccessTypes, #separator, ']]></r><r><![CDATA[') +
']]></r></root>' AS XML)
)
, rs2 AS
(
SELECT rn = ROW_NUMBER() OVER(ORDER BY (t.c))
, Id = c.value('.', 'INT')
FROM rs
CROSS APPLY CardBoardIds.nodes('/root/r/text()') AS t(c)
)
, rs3 AS
(
SELECT rn = ROW_NUMBER() OVER(ORDER BY (t.c))
, Id = c.value('.', 'INT')
FROM rs
CROSS APPLY CardBoardIdsAccessTypes.nodes('/root/r/text()') AS t(c)
)
INSERT INTO #AllowedCardBoardsTable (Id, AccessType)
SELECT rs2.id, rs3.Id
FROM rs2 INNER JOIN rs3 ON rs3.rn = rs2.rn;
-- test
SELECT * FROM #AllowedCardBoardsTable;
Output
+----+------------+
| Id | AccessType |
+----+------------+
| 1 | 11 |
| 2 | 22 |
| 3 | 33 |
| 4 | 44 |
| 5 | 55 |
| 6 | 66 |
+----+------------+
I would suggest you use one of the built-in string-splitting methods, rather than trying to roll your own.
Unfortunately, current versions of SQL Server do not support STRING_SPLIT with an ordinal column. But in this case you can hack it with OPENJSON
DECLARE #AllowedCardBoardIds NVARCHAR(MAX) = '1,2,3,4,5,6';
DECLARE #AllowedCardBoardIdsAccessTypes NVARCHAR(MAX) = '11,22,33,44,55,66';
SELECT
id = acb.value,
AccessType = at.value
FROM OPENJSON('[' + #AllowedCardBoardIds + ']') acb
JOIN OPENJSON('[' + #AllowedCardBoardIdsAccessTypes + ']') at
ON at.[key] = acb.[key];
db<>fiddle
I strongly suggest you store your data properly normalized in the first place, such as in a table variable, temp table, or normal table.

SQL Concatenate Strings in order of line numbers

I am using SQL Server 2014 Standard.
I have the following query...
SELECT ach.amt, ades.dsline, ades.des
FROM ##ACHTrans ach
LEFT OUTER JOIN apvodes ades on 1=1 and ades.vo_id = ach.vo_id
WHERE ades.voline = '100'
ORDER by ach.apnum, ach.cknum, ach.vo_id, ach.amt desc
Which gives me the results...
+------------+---------------+------------------------------+
| ach.amt | ades.dsline | ades.des |
+------------+---------------+------------------------------+
| 1232.50 | 1 | This is the description for |
| 1232.50 | 2 | The $1,232.50 ACH Amount |
| 245.18 | 1 | This one is for the $245.18 |
| 245.18 | 2 | transactions details |
| 245.18 | 3 | that has four lines of info |
| 245.18 | 4 | in the description. |
| 79.25 | 1 | This $79.25 item has 1 line. |
| 15.00 | 1 | So does this $15.00 one. |
+------------+---------------+------------------------------+
I need a way to snag this info by the ach.amt line, and concatenate the ades.des info for results similar to:
+------------+--------------------------------------------------------------------------------------------------+
| Amount | Description |
+------------+--------------------------------------------------------------------------------------------------+
| 1232.50 | This is the description for The $1,232.50 ACH Amount |
| 245.18 | This one is for the $245.18 transactions details that has four lines of info in the description. |
| 79.25 | This $79.25 item has 1 line. |
| 15.00 | So does this $15.00 one. |
+------------+--------------------------------------------------------------------------------------------------+
This is what string_agg() does:
select ach.amt,
string_agg(des, ',') within group (order by dsline)
from t
group by ach.amt;
Without STRING_AGG you would use for XML PATH like so:
DECLARE #table TABLE (amt MONEY, dsline INT, [des] VARCHAR(1000));
INSERT #table VALUES
(1232.50,1,'This is the description for'),
(1232.50,2,'The $1,232.50 ACH Amount'),
( 245.18,1,'This one is for the $245.18'),
( 245.18,2,'transactions details'),
( 245.18,3,'that has four lines of info'),
( 245.18,4,'in the description.'),
( 79.25,1,'This $79.25 item has 1 line.'),
( 15.00,1,'So does this $15.00 one.');
SELECT
amt,
[Description] =
(
SELECT t2.[des]+''
FROM #table AS t2
WHERE t.amt = t2.amt
ORDER BY t2.dsline
FOR XML PATH('')
)
-- string_agg(des, ',') within group (order by dsline)
FROM #table AS t
GROUP BY amt;
Results:
amt Description
--------------------- ---------------------------------------------------------------------------------------------
15.00 So does this $15.00 one.
79.25 This $79.25 item has 1 line.
245.18 This one is for the $245.18transactions detailsthat has four lines of infoin the description.
1232.50 This is the description forThe $1,232.50 ACH Amount
This may not be the prettiest solution but I have had to deal with something similar and used a cursor to concatenate my strings in a temporary table and then used that in my final join statement back to the original table. I used table variables so you can play with it yourself.
Following is a code example you can play with:
declare #tableAmt table (
IDNum int,
Amt Money
)
declare #tableDesc table (
IDNum int,
LineNum int,
Info varchar(10)
)
set nocount on
insert #tableAmt (IDNum, Amt)
values (1,100.00),
(2,125.00)
insert #tableDesc (IDNum, LineNum, Info)
values (1,1,'some text'),
(1,2,'more text'),
(2,1,'different'),
(2,2,'text'),
(2,3,'final')
declare #description table
(IDNum int,
ConcatDesc varchar(30)
)
declare #id int,
#oldid int,
#string char(10),
#finalstring varchar(30)
declare getdata_cursor cursor for
select IDNum, Info
from #tableDesc
order by IDNum, LineNum
open getdata_cursor
fetch next from getdata_cursor into
#id, #string
while ##FETCH_STATUS=0
begin
if #oldid <> #id
begin
insert #description(IDNum, ConcatDesc)
values(#oldid, #finalstring)
select #finalstring = ''
end
select #finalstring = isnull(#finalstring,'') + rtrim(#string) + ' '
select #string = '', #oldid = #id
fetch next from getdata_cursor into
#id, #string
end
insert #description(IDNum, ConcatDesc)
values(#oldid, #finalstring)
close getdata_cursor
deallocate getdata_cursor
select ta.IDNum, Amt, ConcatDesc from #tableAmt ta join #description d
on ta.IDNum = d.IDNum

How can I do something like "STRING_AGG" in Sql Server Compact?

everybody
I want to make something like STRING_AGG in Sql Server Compact.
For example, I want to flatten the code column in the table below:
+----+--------+
| Id | Code |
+----+--------+
| 1 | 256987 |
| 1 | 256985 |
| 1 | 356994 |
+----+--------+
So I will get something like that:
+----+------------------------+
| Id | Codes |
+----+------------------------+
| 1 | 256987, 256985, 356994 |
+----+------------------------+
Thanks in advance!
Your best bet will be to do it using C# (string.Join).
There a couple of ways to do this:
1: Using COALESCE
DECLARE #Tbl TABLE
(
Name VARCHAR(20)
);
INSERT INTO #Tbl VALUES
('Jim'),
('Tim'),
('Kim');
DECLARE #ReturnVar VARCHAR(256);
SELECT *
FROM #Tbl;
SELECT #ReturnVar = COALESCE(#ReturnVar + ', ', '') + Name
FROM #Tbl;
SELECT #ReturnVar;
2: Using XML
DECLARE #Tbl TABLE
(
Name VARCHAR(20)
);
INSERT INTO #Tbl VALUES
('Jim'),
('Tim'),
('Kim');
DECLARE #ReturnVar VARCHAR(256);
SELECT STUFF((SELECT ',' + Name
FROM #Tbl
FOR XML PATH('')),1,1,'') AS Name;
You can find a bit more detail here.

How to add a Column to stored procedure result?

I have the following sql procedure:
DECLARE #temp table
(
Column1 nvarchar(1000)
)
INSERT #temp (Column1)
SELECT fld_4
FROM MyTable
WHERE fld_1 = #param1 and
fld_2 = #param2 and
fld_3 = #param3
SELECT ROW_NUMBER() OVER(ORDER BY Column1 ASC) AS Number, Split.a.value('.', 'VARCHAR(100)') AS Result
FROM
(
SELECT Column1,
CAST ('<M>' + REPLACE(Column1, ';', '</M><M>') + '</M>' AS XML) AS Result
FROM #temp
) AS A CROSS APPLY Result.nodes ('/M') AS Split(a);
Structure of MyTable:
| fld_1 | fld_2 | fld_3 | fld_4 | ... | fld_9 | ...|
Where fld_4 contains something like this:
-9;-9;-1;-9;-9;-9;-9;-9;-1;-9;-9;-9;-9;-9;-9;-9;-9;-9;-1;-9;-9;-9;-9;-9;-9;-9;-9;-9;-1;-9;-1;-9;-9;-9;-1;-9;-9;-9;-9;-9;-9;-1;-1;-1;-1;-9;-1;-1;-9;-9;-9;-9;-1;-9;-1;-9;-9;-9;-1;-9;-1;-9;-1;-9;-9;-9;-9;-1;-9;-9;-1;-1;-9;-1;-1;0000;FFF8;-9;-9;-9;-1;-9;-1;-9;FFF6;-9;-1;-9;-1;-9;-1;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9
My procedure returns a table with this structure:
| Number | Result |
| 1 | -9 |
| 2 | -9 |
| 3 | -1 |
| ... | ... |
Now, I want to achieve the following result:
| Number | Result | NewColumn |
| 1 | -9 | Value of fld_9 |
| 2 | -9 | Value of fld_9 |
| 3 | -1 | Value of fld_9 |
| ... | ... | Value of fld_9 |
Any suggestions?
You cannot call a Stored Procedure result directly..
However you can make view or or table-valued user-defined function then get results..
Other way insert Stored Procedure result on TempTable
INSERT INTO #tempTable EXEC MyStoredProcedure
look at this Quick Sample
Create PROCEDURE SampleStoreProc
AS
BEGIN
Select 'Burak', 1
END
GO
Create Table #TempTable
(
MyCol Varchar(50),
ReferanceCol int
)
Insert into #TempTable Exec SampleStoreProc
go
Create Table TestTable2
(
MyCol2 varchar(250),
RefCol int
);
go
Insert into TestTable2 values ('Yeni', 1);
Select a.MyCol, b.MyCol2 From #TempTable a
left join TestTable2 b on b.RefCol = a.ReferanceCol
If I understand what you are asking, you simply want another column included in your result set. Something like the following snippet should work. Keep your FROMclause, and add , MyTable to the end of it.
...
SELECT
ROW_NUMBER() OVER(ORDER BY Column1 ASC) AS Number
, Split.a.value('.', 'VARCHAR(100)') AS Result
, fld_9 AS NewColumn
FROM
...
, MyTable
WHERE
MyTable.fld_1 = #param1 AND
MyTable.fld_2 = #param2 AND
MyTable.fld_3 = #param3;

SQL Server convert select a column and convert it to a string

Is it possible to write a statement that selects a column from a table and converts the results to a string?
Ideally I would want to have comma separated values.
For example, say that the SELECT statement looks something like
SELECT column
FROM table
WHERE column<10
and the result is a column with values
|column|
--------
| 1 |
| 3 |
| 5 |
| 9 |
I want as a result the string "1, 3, 5, 9"
You can do it like this:
Fiddle demo
declare #results varchar(500)
select #results = coalesce(#results + ',', '') + convert(varchar(12),col)
from t
order by col
select #results as results
| RESULTS |
-----------
| 1,3,5,9 |
There is new method in SQL Server 2017:
SELECT STRING_AGG (column, ',') AS column FROM Table;
that will produce 1,3,5,9 for you
select stuff(list,1,1,'')
from (
select ',' + cast(col1 as varchar(16)) as [text()]
from YourTable
for xml path('')
) as Sub(list)
Example at SQL Fiddle.
SELECT CAST(<COLUMN Name> AS VARCHAR(3)) + ','
FROM <TABLE Name>
FOR XML PATH('')
The current accepted answer doesn't work for multiple groupings.
Try this when you need to operate on categories of column row-values.
Suppose I have the following data:
+---------+-----------+
| column1 | column2 |
+---------+-----------+
| cat | Felon |
| cat | Purz |
| dog | Fido |
| dog | Beethoven |
| dog | Buddy |
| bird | Tweety |
+---------+-----------+
And I want this as my output:
+------+----------------------+
| type | names |
+------+----------------------+
| cat | Felon,Purz |
| dog | Fido,Beethoven,Buddy |
| bird | Tweety |
+------+----------------------+
(If you're following along:
create table #column_to_list (column1 varchar(30), column2 varchar(30))
insert into #column_to_list
values
('cat','Felon'),
('cat','Purz'),
('dog','Fido'),
('dog','Beethoven'),
('dog','Buddy'),
('bird','Tweety')
)
Now – I don’t want to go into all the syntax, but as you can see, this does the initial trick for us:
select ',' + cast(column2 as varchar(255)) as [text()]
from #column_to_list sub
where column1 = 'dog'
for xml path('')
--Using "as [text()]" here is specific to the “for XML” line after our where clause and we can’t give a name to our selection, hence the weird column_name
output:
+------------------------------------------+
| XML_F52E2B61-18A1-11d1-B105-00805F49916B |
+------------------------------------------+
| ,Fido,Beethoven,Buddy |
+------------------------------------------+
You can see it’s limited in that it was for just one grouping (where column1 = ‘dog’) and it left a comma in the front, and additionally it’s named weird.
So, first let's handle the leading comma using the 'stuff' function and name our column stuff_list:
select stuff([list],1,1,'') as stuff_list
from (select ',' + cast(column2 as varchar(255)) as [text()]
from #column_to_list sub
where column1 = 'dog'
for xml path('')
) sub_query([list])
--"sub_query([list])" just names our column as '[list]' so we can refer to it in the stuff function.
Output:
+----------------------+
| stuff_list |
+----------------------+
| Fido,Beethoven,Buddy |
+----------------------+
Finally let’s just mush this into a select statement, noting the reference to the top_query alias defining which column1 we want (on the 5th line here):
select top_query.column1,
(select stuff([list],1,1,'') as stuff_list
from (select ',' + cast(column2 as varchar(255)) as [text()]
from #column_to_list sub
where sub.column1 = top_query.column1
for xml path('')
) sub_query([list])
) as pet_list
from #column_to_list top_query
group by column1
order by column1
output:
+---------+----------------------+
| column1 | pet_list |
+---------+----------------------+
| bird | Tweety |
| cat | Felon,Purz |
| dog | Fido,Beethoven,Buddy |
+---------+----------------------+
And we’re done.
You can read more here:
FOR XML PATH in SQL server and [text()]
https://learn.microsoft.com/en-us/sql/relational-databases/xml/use-path-mode-with-for-xml?view=sql-server-2017
https://www.codeproject.com/Articles/691102/String-Aggregation-in-the-World-of-SQL-Server
This a stab at creating a reusable column to comma separated string. In this case, I only one strings that have values and I do not want empty strings or nulls.
First I create a user defined type that is a one column table.
-- ================================
-- Create User-defined Table Type
-- ================================
USE [RSINET.MVC]
GO
-- Create the data type
CREATE TYPE [dbo].[SingleVarcharColumn] AS TABLE
(
data NVARCHAR(max)
)
GO
The real purpose of the type is to simplify creating a scalar function to put the column into comma separated values.
-- ================================================
-- Template generated from Template Explorer using:
-- Create Scalar Function (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Rob Peterson
-- Create date: 8-26-2015
-- Description: This will take a single varchar column and convert it to
-- comma separated values.
-- =============================================
CREATE FUNCTION fnGetCommaSeparatedString
(
-- Add the parameters for the function here
#column AS [dbo].[SingleVarcharColumn] READONLY
)
RETURNS VARCHAR(max)
AS
BEGIN
-- Declare the return variable here
DECLARE #result VARCHAR(MAX)
DECLARE #current VARCHAR(MAX)
DECLARE #counter INT
DECLARE #c CURSOR
SET #result = ''
SET #counter = 0
-- Add the T-SQL statements to compute the return value here
SET #c = CURSOR FAST_FORWARD
FOR SELECT COALESCE(data,'') FROM #column
OPEN #c
FETCH NEXT FROM #c
INTO #current
WHILE ##FETCH_STATUS = 0
BEGIN
IF #result <> '' AND #current <> '' SET #result = #result + ',' + #current
IF #result = '' AND #current <> '' SET #result = #current
FETCH NEXT FROM #c
INTO #current
END
CLOSE #c
DEALLOCATE #c
-- Return the result of the function
RETURN #result
END
GO
Now, to use this. I select the column I want to convert to a comma separated string into the SingleVarcharColumn Type.
DECLARE #s as SingleVarcharColumn
INSERT INTO #s VALUES ('rob')
INSERT INTO #s VALUES ('paul')
INSERT INTO #s VALUES ('james')
INSERT INTO #s VALUES (null)
INSERT INTO #s
SELECT iClientID FROM [dbo].tClient
SELECT [dbo].fnGetCommaSeparatedString(#s)
To get results like this.
rob,paul,james,1,9,10,11,12,13,14,15,16,18,19,23,26,27,28,29,30,31,32,34,35,36,37,38,39,40,41,42,44,45,46,47,48,49,50,52,53,54,56,57,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,81,82,83,84,87,88,90,91,92,93,94,98,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,120,121,122,123,124,125,126,127,128,129,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159
I made my data column in my SingleVarcharColumn type an NVARCHAR(MAX) which may hurt performance, but I flexibility was what I was looking for and it runs fast enough for my purposes. It would probably be faster if it were a varchar and if it had a fixed and smaller width, but I have not tested it.
ALTER PROCEDURE [dbo].[spConvertir_CampoACadena]( #nomb_tabla varchar(30),
#campo_tabla varchar(30),
#delimitador varchar(5),
#respuesta varchar(max) OUTPUT
)
AS
DECLARE #query varchar(1000),
#cadena varchar(500)
BEGIN
SET #query = 'SELECT #cadena = COALESCE(#cadena + '''+ #delimitador +''', '+ '''''' +') + '+ #campo_tabla + ' FROM '+#nomb_tabla
--select #query
EXEC(#query)
SET #respuesta = #cadena
END
You can use the following method:
select
STUFF(
(
select ', ' + CONVERT(varchar(10), ID) FROM #temp
where ID<50
group by ID for xml path('')
), 1, 2, '') as IDs
Implementation:
Declare #temp Table(
ID int
)
insert into #temp
(ID)
values
(1)
insert into #temp
(ID)
values
(3)
insert into #temp
(ID)
values
(5)
insert into #temp
(ID)
values
(9)
select
STUFF(
(
select ', ' + CONVERT(varchar(10), ID) FROM #temp
where ID<50
group by ID for xml path('')
), 1, 2, '') as IDs
Result will be:
--------------------------- easy I Found Like it ----------------
SELECT STUFF((
select ','+ name
from tblUsers
FOR XML PATH('')
)
,1,1,'') AS names
name
---------
mari, joan, carls
---------
Use LISTAGG function,
ex. SELECT LISTAGG(colmn) FROM table_name;
Use simplest way of doing this-
SELECT GROUP_CONCAT(Column) from table
+------+----------------------+
| type | names |
+------+----------------------+
| cat | Felon |
| cat | Purz |
| dog | Fido |
| dog | Beethoven |
| dog | Buddy |
| bird | Tweety |
+------+----------------------+
select group_concat(name) from Pets
group by type
Here you can easily get the answer in single SQL and by using group by in your SQL you can separate the result based on that column value. Also you can use your own custom separator for splitting values
Result:
+------+----------------------+
| type | names |
+------+----------------------+
| cat | Felon,Purz |
| dog | Fido,Beethoven,Buddy |
| bird | Tweety |
+------+----------------------+