Flatten SQL Server Table to a string - sql

I have a table like:
ID | Value
----------------
1 | One
2 | Two
3 | Three
What I need to do is create a single string from these values, in the format:
'1: One, 2: Two, 3: Three'
I know how to do this using cursors, but it will be used as a column in a view, so it's not really a performant option.
Any pointers?

WITH T(ID,Value) AS
(
SELECT 1, 'One' UNION ALL
SELECT 2, 'Two' UNION ALL
SELECT 3, 'Three'
)
SELECT STUFF(
(SELECT ', ' + CAST(ID as varchar(11)) + ': ' + Value
FROM T
FOR XML PATH (''))
, 1, 2, '')

Have a look at something like
DECLARE #Table TABLE(
ID INT,
Value VARCHAR(20)
)
INSERT INTO #Table SELECT 1,'One'
INSERT INTO #Table SELECT 2,'Two'
INSERT INTO #Table SELECT 3,'Three'
SELECT STUFF(
(
SELECT ', ' + CAST(ID AS VARCHAR(MAX)) + ': ' + Value
FROM #Table
FOR XML PATH(''), TYPE
).value('.','varchar(max)')
,1,2, ''
)

SELECT STUFF((
SELECT ' ' + CAST(ID AS VARCHAR(2)) + ': '+ Value
FROM dbo.Table
FOR XML PATH('')
), 1, 1, ''
) As concatenated_string

DECLARE #ans VARCHAR(max)
SET #ans=''
SELECT #ans = #ans + str(id)+':'+value FROM table
SELECT #ans
Change the max to 8000 if your version of SQL doesn't support it

I would simply not do this in the database if at all possible. It's not designed for formatting data in a certain way; let the calling application handle that.
In C# (assuming data is an instance of SqlDataReader):
var l = new List<string>();
while (reader.Read())
l.Add(string.Format("{0}: {1}", reader[0], reader[1]));
var s = string.Join(", ", l.ToArray());

Related

Insert Result of Select into Variable with Order By

Data
Approval_ID
-----------
1
2
3
4
5
6
7
8
9
10
Query
DECLARE
#id varchar(8000)
SELECT #id = COALESCE(#id + ', ', '') + '[' + Approval_ID + ']'
FROM (
SELECT DISTINCT Approval_ID
FROM Gate_III_CS_Approval
) Y
Result always
1,10,2,3,4,5,6,7,8,9
I've tried to add Order By
ORDER BY len(Approval_ID), Approval_ID
but have error
The ORDER BY clause is invalid in views, inline functions, derived
tables, subqueries, and common table expressions, unless TOP, OFFSET
or FOR XML is also specified.
and I want to the result like this
1,2,3,4,5,6,7,8,9,10
Whats should I do?
Update :
;with cte as (
SELECT DISTINCT Approval_ID
FROM Gate_III_CS_Approval
)
SELECT #id = STUFF(
(SELECT concat(',', '[' + Approval_ID + ']')
FROM cte ORDER BY len(Approval_ID), Approval_id
FOR XML PATH('')
), 1, 1, '')
Using CTE and STUFF for XML PATH
-- replace CTE with your table, this is only an example
declare #id varchar(8000)
;with cte as (
select 1 n
union all
select n+1 n from
cte
where n < 10
)
select #id =
STUFF((
SELECT concat(',', n)
FROM cte
order by n
FOR XML PATH('')
), 1, 1, '')
select #id
programmatically cast n from alphanumeric to int for sorting
It seems you are using a varchar field instead of an integer for Approval_ID.
For ordering it based on the varchar field, you can try the method from maSTAShuFu's answer.
Here I am updating it with your query from question.
SELECT STUFF(
(SELECT CONCAT(',[', Approval_ID,']')
FROM <your_table>
ORDER BY cast(Approval_ID as int)
FOR XML PATH('')), 1, 1, '')
Maybe you can try to convert varchar to int for this purpose. I built an example here
DECLARE
#id varchar(8000)
SELECT #id = COALESCE(#id + ', ', '') + '[' + CAST(ID AS VARCHAR(10)) + ']'
FROM (
SELECT DISTINCT CAST(id AS INT) ID
FROM TABLA
) Y
SELECT #ID

Concatenate column values based on type result

Declare #name nvarchar(max),#Id int
SELECT #Id=[EmpType],#name =ISNULL(#name + ',','')+[UserName] FROM [dbo].[TestTable]
Group by [EmpType]
SELECT #Id,#name
Getting error with this code, How can i get the result employee type wise concatenated usernames
Expecting Result set
You can try below using STUFF() function
SELECT [EmpType], abc = STUFF(
(SELECT ',' + [UserName]
FROM [dbo].TestTable] t1
WHERE t1.[EmpType] = t2.[EmpType]
FOR XML PATH (''))
, 1, 1, '') from [dbo].TestTable] t2
group by [EmpType];

Replace a value in a comma separated string in SQL Server database

I'm using a SQL Server 2014 database and I have a column that contains comma-separated values such as:
1,2,3
4,5
3,6,2
4,2,8
2
What I need to do is to replace the number 2 with the number 3 (string values) in each record and not duplicate the 3 if possible. I'm not sure that this can be done unless I use a function and I'm not sure how to do it in a function.
I think I need to split a string into a table and then loop the values and put it back together with the new value. Is there an easier way? Any help is appreciated.
Expect output would therefore be:
1,3
4,5
3,6
4,3,8
3
While it is possible, I do not encourage this:
DECLARE #old AS VARCHAR(3) = '2';
DECLARE #new AS VARCHAR(3) = '3';
WITH opdata(csv) AS (
SELECT '1,22,3' UNION ALL
SELECT '1,2,3' UNION ALL
SELECT '4,5' UNION ALL
SELECT '3,6,2' UNION ALL
SELECT '4,2,8' UNION ALL
SELECT '2'
), cte1 AS (
SELECT
csv,
CASE
WHEN ',' + csv + ',' LIKE '%,' + #old + ',%' THEN
CASE
WHEN ',' + csv + ',' LIKE '%,' + #new + ',%' THEN REPLACE(',' + csv + ',', ',' + #old + ',', ',') -- new already present so just delete old
ELSE REPLACE(',' + csv + ',', ',' + #old + ',', ',' + #new + ',') -- replace old with new
END
ELSE ',' + csv + ','
END AS tmp
FROM opdata
)
SELECT
csv,
STUFF(STUFF(tmp, 1, 1, ''), LEN(tmp) - 1, 1, '') AS res
FROM cte1
Result:
csv | res
-------+-------
1,22,3 | 1,22,3
1,2,3 | 1,3
4,5 | 4,5
3,6,2 | 3,6
4,2,8 | 4,3,8
2 | 3
Note that the plethora of ',...,' is required to avoid replacing values such as 22. If you are using SQL Server 2017 you can ditch the extra CTE + STUFF and use TRIM(',' FROM ...).
This isn't going to perform particularly well, however:
WITH CTE AS (
SELECT *
FROM (VALUES ('1,2,3'),
('4,5'),
('3,6,2'),
('4,2,8'),
('2')) V(DS))
SELECT CASE WHEN DS LIKE '%3%' THEN REPLACE(REPLACE(DS,'2,',''),',2','')
WHEN DS LIKE '%2%' THEN REPLACE(DS,'2','3')
ELSE DS
END
FROM CTE;
May be you are looking something like this.
SELECT REPLACE(CASE WHEN CHARINDEX('2', '1,2,3') > 0 THEN REPLACE('1,2,3', '2','') ELSE REPLACE('1,2,3', '2','3') END, ',,',',')
I have taken a hard coded value for demonstration. You can replace'1,2,3' with column name in the table.
To update:
DECLARE #was nvarchar(2) = 2,
#willbe nvarchar(2) = 3,
#d nvarchar(1) = ','
UPDATE strings
SET string = REVERSE(
STUFF(
REVERSE(
STUFF(
CASE WHEN CHARINDEX(#d+#willbe+#d,#d+string+#d) > 0
THEN REPLACE(#d+string+#d,#d+#was+#d,#d)
ELSE REPLACE(#d+string+#d,#d+#was+#d,#d+#willbe+#d)
END,1,1,'')
),1,1,''))
Output:
1,3
4,5
3,6
4,3,8
3

Different SQL Select query

I need to write SQL query in order to extract some data.
i have this data in my table:
ID Store Value
1 9921 NOK
2 9921 NOK1
3 9921 OK3
what i need is to get data from select query like this form:
9921 NOK,NOK1,OK3
Any help please ?
You can use STUFF:
SELECT DISTINCT Store,
STUFF((SELECT ',' + Value
FROM Your_Table
WHERE Store = 9921
FOR XML PATH('')), 1, 1, '')
FROM Your_Table
Try to accomplish your excepted output by using COALESCE;
Create a sample table for testing purpose
CREATE TABLE SampleData (id INT ,store INT ,value NVARCHAR(50))
INSERT INTO SampleData VALUES (1 ,9921 ,'NOK')
INSERT INTO SampleData VALUES (2 ,9921 ,'NOK1')
INSERT INTO SampleData VALUES (3 ,9921 ,'NOK2')
Create a Scalar-Valued Function
Alter FUNCTION fun_GetCombinedData
(
#store int
)
RETURNS nvarchar(max)
AS
BEGIN
-- Declare the return variable here
DECLARE #CombineValue nvarchar(max)
SELECT #CombineValue = COALESCE(#CombineValue + ', ', '') + value
FROM SampleData where store=#store
RETURN #CombineValue
END
GO
Final Query,
SELECT store
,dbo.fun_GetCombinedData(store) AS value
FROM SampleData
GROUP BY store
Expected Output:
store | value
------------------------
9921 | NOK,NOK1,NOK2
This is one of the way to simplify your select query.
Using T-SQL we can do it this way:
declare #store int = 9921, #values varchar(max) = ''
select #values = #values
+ case
when #values = '' then ''
else ','
end + value
from table_name
where store = #store
order by id
select #store, #values
Go through this below example
Demo: [SQLFiddle]
The SQL I used is as below,
SELECT
store,
STUFF(
(SELECT DISTINCT ',' + value
FROM SampleData
WHERE store = a.store
FOR XML PATH (''))
, 1, 1, '') AS CombineValues
FROM SampleData AS a
GROUP BY store
you will see your expected result as "CombineValues"
store CombineValues
9921 NOK,NOK1,NOK2

Get the value of a column replacing the comma separator

How can I get each value of a column that has a comma separator in her value ?
Example:
ID ColumnUnified
1 12,34,56,78
2 80,99,70,56
What I want is a query to get the number without comma. If possible, in collumns.
12 34 56 78
This will work for any number of values http://beyondrelational.com/modules/2/blogs/70/posts/10844/splitting-delimited-data-to-columns-set-based-approach.aspx
The solution Madhivanan's link refers to is very creative, but I had a slight problem with it on SQL Server 2012 related to the name of one of the columns (Start). I've modified the code in his answer to use StartPos instead of Start for the column name.
I was not familiar with the system procedure spt_values, but I found a very informative description of the procedure here on SO for those who are interested in exactly how this solution works.
Finally, here's the (slightly) revised code from Madhivana's answer:
CREATE TABLE #test(id int, data varchar(100))
INSERT INTO #test VALUES (1,'This,is,a,test,string')
INSERT INTO #test VALUES (2,'See,if,it,can,be,split,into,many,columns')
DECLARE #pivot varchar(8000)
DECLARE #select varchar(8000)
SELECT #pivot = COALESCE(#pivot + ',', '') + '[col'
+ CAST(number + 1 AS VARCHAR(10)) + ']'
FROM master..spt_values
WHERE type = 'p'
AND number <= ( SELECT MAX(LEN(data) - LEN(REPLACE(data, ',', '')))
FROM #test
)
SELECT #select = '
select p.*
from (
select
id,substring(data, StartPos+2, endPos-StartPos-2) as token,
''col''+cast(row_number() over(partition by id order by StartPos) as varchar(10)) as n
from (
select
id, data, n as StartPos, charindex('','',data,n+2) endPos
from (select number as n from master..spt_values where type=''p'') num
cross join
(
select
id, '','' + data +'','' as data
from
#test
) m
where n < len(data)-1
and substring(data,n+1,1) = '','') as data
) pvt
Pivot ( max(token)for n in (' + #pivot + '))p'
EXEC(#select)
DROP TABLE #test