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

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.

Related

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

PostgreSQL: Check if substring is in a string and if true then replace the entire string with the substring

I have a column in a table like this:
| biz_name |
---------------
| www.Dog.com |
| Dog LLC. |
| Dog Inc. |
| www.Cat.com |
| Cat Corp |
And for each element in the column, I want to check if it contains the substring 'Dog' or 'Cat' and if it does, then to replace the entire string with either 'Dog' or 'Cat'.
The results should be:
| biz_name |
---------------
| Dog |
| Dog |
| Dog |
| Cat |
| Cat |
Is there a way to do this without using CASE WHEN as such:
CASE
WHEN biz_name ilike '%Dog%' THEN 'Dog'
WHEN biz_name ilike '%Cat%' THEN 'Cat'
ELSE biz_name END as biz_name
The above table is just an example to demonstrate what I'm trying to do, but the actual table I'm working on has many more substrings I'm trying to search for and replace with that using multiple CASE WHEN statements can get tedious. Does anyone have a more efficient way to do it? Thanks.
1) can you do a quick insert into a temp table
--assuming table name is biz
declare #name varchar(max)
declare #TEMP table (Name varchar(max))
-- insert all your values
insert into #TEMP values ('dog')
insert into #TEMP values ('cat')
set #name = select top 1 name from #TEMP
delete from #temp where name = #name -- remove from que /table
WHILE #name IS NOT NULL
BEGIN
update dbo.biz
set biz_name = #name
where biz_name like '%' + #name '%'
set #name = select top 1 name from #TEMP
delete from #TEMP where name = #name
END

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 Pivot is inserting NULL values

Please find the table (OututTable) that needs to be transposed. Here the QuestionID is formed by concatenating two values -[Question:AnswerID]
refID | SessionID | QuestionID | AnswerValue
9000 | 205545715 | [4907] | Good morning
12251 | 205543469 | [10576:16307] | 3
12255 | 205543469 | [10907:17001] | 4
13157 | 205543703 | [10576:16307] | 3
14387 | 205543493 | [10907:17001] | 2
14389 | 205543493 | [10911:17007] | 3
The expected output should have one row per SessionID and the number of columns are dynamic
SessionID | [4097] | [10576:16307] | [10907:17001] | [10911:17007]
205545715 |Good morning | | |
205543469 | | 3 | 4 |
205543703 | | 3 | |
205543493 | | | 2 | 3
I have the output in the above format but there are only NULL values inserted instead of Answer values
I am thinking there might a mismatch in column names. Any help would be great! please let me know.
Code:
set #Questions = (STUFF((SELECT distinct ',[' + cast(i.SessionID as varchar(20)) + ']'
FROM OutputTable i
FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, ''))
print #Questions
set #SQLQuery = 'select QuestionID,'+ #Questions +' from '+'('+ 'select SessionID,QuestionID,AnswerValue from OutputTable '+ ') p '+ 'PIVOT'+ '('+'max(Answervalue)'+'FOR p.SessionID IN ('+ #Questions +')' +') as pvt'
Great Question! The problem is with the brackets in the QuestionID. While these are necessary for the Pivot Column Aliases, these don't work as string filters.
The code sample also switches QuestionID and SessionID for the expected output.
This code will return the expected output, sorted slightly differently. A temp table is created here to simulate the OutputTable object. This will need to be switched out with the DB Table.
declare
#Questions varchar(max),
#SQLQuery varchar(max)
create table #OutputTable
(
refID int,
SessionID int,
QuestionID varchar(50),
AnswerValue varchar(50)
)
insert into #OutputTable
values
(9000,205545715,'[4907]','Good morning'),
(12251,205543469,'[10576:16307]','3'),
(12255,205543469,'[10907:17001]','4'),
(13157,205543703,'[10576:16307]','3'),
(14387,205543493,'[10907:17001]','2'),
(14389,205543493,'[10911:17007]','3')
set #Questions = (STUFF((SELECT distinct ',' + cast(i.QuestionID as varchar(20))
FROM #OutputTable i
FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, ''))
set #SQLQuery = '
select SessionID,'+ #Questions +'
from (
select
SessionID,
replace(replace(QuestionID,''['',''''),'']'','''') QuestionID,
AnswerValue
from #OutputTable
) p
PIVOT (
max(Answervalue)
FOR p.QuestionID IN ('+ #Questions +')
) as pvt
order by SessionID desc'
exec(#SQLQuery)

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 |
+------+----------------------+