Execute stored procedure with parameter from other table - sql

I have a procedure with one parameter, letsay #AssetID int.
I want to select a column value from another table, then use that value as the parameter for this procedure.
I've stored procedure something like this and the table has been filtered with "Where" criteria from #AssetID parameter:
declare #inspectyear as nvarchar(max), #calc as nvarchar(max), #query as nvarchar(max);
set #inspectyear = STUFF((select distinct ',' + quotename(InspectYear) from ##t2 c
for XML path(''), type).value('.','NVARCHAR(MAX)'),1,1,'')
select #calc = ', ' + quotename(Max(InspectYear)) + ' - ' + quotename(Max(InspectYear)-2)
+ ' as Calc1, ' + quotename(Max(InspectYear)) + ' - ' + quotename(min(InspectYear))
+ ' as Calc2' from #t2;
set #query =
';with data as
(
select inspectyear,
partno, Pos, number
from #t2
unpivot
(
number
for Pos in ([Pos1], [Pos2], [Pos3], [Pos4])
) unpvt
)
select * ' + #calc + ' into ##temp
from data
pivot
(
sum(number)
for inspectyear in (' + #inspectyear + ')
) pvt
order by partno';
exec sp_executesql #query = #query;
select * from ##temp;
drop table ##temp;
So I need to create another procedure, for instance:
create procedure spExecmyProc
as
begin
exec spMyProc '#AssetID' -- <-- The parameter took from other table.
go
end
The #date parameter, took from other table.
Is it possible to do that? The result should be only one result.
So far, this is what I did. It works, but the result is not on "one result". It create more than one result if the #AssetID is more than one:
declare #AssetID int;
declare cur CURSOR FOR
select distinct AssetID from myTable
open cur
fetch next from cur into #AssetID
while ##FETCH_STATUS = 0
begin
exec mySPName #AssetID
fetch next from cur into #AssetID
end
close cur
DEALLOCATE cur
Thank you.

I'm not 100% sure I understand what you're trying to achieve, but if you want to be able to be able to run some code on each value of AssetID in mytable, returning just one result for each input value, I think you could use a Scalar-valued Function. Let's pretend that the purpose of your original stored procedure was just to increment the AssetId value by 1 for simplicity - your function could be created like this:
CREATE FUNCTION fnMyFunction (#AssetId INT)
RETURNS INT
AS
BEGIN
DECLARE #return INT
SET #return = #AssetId + 1
RETURN #return
END
If you then have some values in a table:
CREATE TABLE Assets (
AssetId INT
)
INSERT INTO Assets
SELECT 1
UNION
SELECT 2
UNION
SELECT 3
UNION
SELECT 5
UNION
SELECT 7
UNION
SELECT 5
You can call your function on each value you return:
SELECT AssetId,
dbo.fnMyFunction(AssetId) AS AssetIdPlus1
FROM Assets
Which gives these results for my super simple dataset defined above:
/------------------------\
| AssetId | AssetIdPlus1 |
|---------+--------------|
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
| 5 | 6 |
| 7 | 8 |
| 5 | 6 |
\------------------------/
If you just want to get the result for each unique value of AssetId in your table, then just return the DISTINCT results:
SELECT DISTINCT
AssetId,
dbo.fnMyFunction(AssetId)
FROM Assets
which would give these results for the same dataset above (with just one row for AssetId = 5):
/------------------------\
| AssetId | AssetIdPlus1 |
|---------+--------------|
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
| 5 | 6 |
| 7 | 8 |
\------------------------/

Related

Merge two rows in SQL with only one column being different

Assuming I have a table containing the following information:
FK | Field1 | Field2
---+--------+--------
4 | 103 | 5836
4 | 103 | 5835
FK | Field1 | Field2 | Field2A
---+--------+--------+--------
4 | 103 | 5836 | 5835
Thanks
i think you really need PIVOT, but for an exact dataset in the question, you can follow an approach like below, it's kinda weird and in T-SQl:
declare #a as int
declare #b as int
declare #c as int
declare #query Varchar(Max)
set #query = 'Select 4,103'
DECLARE curs CURSOR FOR
select * From
(select 4 as a , 103 as b , 5836 as c
Union select 4 as a , 103 as b , 5835 as c) as res
OPEN curs
FETCH NEXT FROM curs
INTO #a,#b,#c
WHILE ##FETCH_STATUS = 0
BEGIN
set #query = #query + ','+cast(#c as varchar)
FETCH NEXT FROM curs
INTO #a,#b,#c
END
CLOSE curs;
DEALLOCATE curs;
EXEC(#query)

left join of 3 tables and display like a dynamic pivot

i have 3 tables:
payorderType :
---------
typeID | TypeName |
1 | accounting |
2 | budget |
----------
step:
----------
StepID | StepName | typeID
1 | payorder | 1
2 | cheque | 1
3 | cheque | 2
----------
user:
----------
userID | StepName | StepID
7878 | payorder | 1
4547 | cheque | 2
6538 | cheque | 1
----------
I want to make a table which users exists in row and columns includes with concat of step and payorderType. same as below:
users | accounting_payorder | accounting_cheque | budget_cheque |
7878 | 1 | 0 | 0 |
4547 | 0 | 1 | 0 |
6538 | 0 | 1 | 0 |
My quesdtion is : if i don't know number of payorderType rows and number of step rows, how should i write it?
My Script is here :
First I create a table in cursor for concat payorderType and step:
CREATE PROC sp_payOrderType
AS
BEGIN
DECLARE a CURSOR
FOR SELECT DISTINCT p.TypeName,s.StepName
FROM
dbo.PayOrderType p LEFT JOIN
dbo.vStep s ON s.TypeID = p.TypeID
FOR READ ONLY
DECLARE #payOrderType NVARCHAR(50),#stepName NVARCHAR(50)
DECLARE #SQL NVARCHAR(MAX)=''
OPEN a
FETCH NEXT FROM a INTO #payOrderType, #stepName
WHILE ##FETCH_STATUS=0
BEGIN
DECLARE #b VARCHAR(max), #b2 VARCHAR(max)
SELECT #b = ISNULL(#b ,'') +'['+ ISNULL(#payOrderType ,'')+ '____'+ISNULL(#stepName ,'')+ ']'+ ' NVARCHAR(1000) ,'
FETCH NEXT FROM a INTO #payOrderType,#stepName
END
CLOSE a
DEALLOCATE a
SELECT #SQL = 'ALTER table AA(' + SUBSTRING(#b,1, LEN(#b)-1) + ')'
SELECT #SQL
END
but i don't know how i should relate rows(userID) with columns ?
You should have determined output structure. Its little risky to have variable output structure.
But here we go:
Make your structure simple (remove most of variables) - create view (or use derived table) payorderType + step
-- should be inner join probably instead of left join
-- if you use left join you have to isnull s.StepName
SELECT
u.userID,
s.StepID,
p.TypeName,
s.StepName,
p.TypeName + '_' + s.StepName StepType,
-- Your column can be like `coalesce(p.TypeName + '_' + s.StepName, p.TypeName, s.StepName) StepType` for left joins
1 Point
FROM dbo.PayOrderType p
INNER JOIN dbo.vStep s ON s.TypeID = p.TypeID
INNER JOIN dbo.user u ON u.StepID = s.StepID
Make your queries more clear (can all yours fields have null values?. Now you can work with only one column/variable.
Now is time for pivot:
SELECT
userID,
[accounting_payorder],
[accounting_cheque],
[budget_cheque]
FROM newview v
PIVOT(MAX(point) FOR StepType in ([accounting_payorder], [accounting_cheque], [budget_cheque])
If its necessary you can use dynamic query:
declare #header varchar(max),
#columns varchar(max)
select #header = coalesce(#header + ', ', '') + 'isnull(''' + StepType + ''', 0) ' + '[' + StepType + ']',
#columns = coalesce(#columns + ', ', '') + '[' + StepType + ']'
from newview
group by StepType
declare #sqlpvt varchar(4000) -- limited by lenght of exec statement
set #sqlpvt = 'select userID, $HEADER FROM newview v PIVOT(MAX(point) FOR StepType in ($COLUMNS)'
-- replace pseudovariables
set #sqlpvt = replace(#sqlpvt, '$HEADER', #header)
set #sqlpvt = replace(#sqlpvt, '$COLUMNS', #columns)
print #sqlpvt
exec (#sqlpvt)
Sorry if somethink is wrong (writed on blind), but i think for guide it's enough. But you should prefer end on step 2 (non-static code is dangerous).

SQL Evaluate formula stored in database

Is it possible to evaluate a string formula/expression stored in a column? (SQL Server 2014).
Example:
TABLE:
ID | Formula
1 | IIF(2<3,'A','B')
2 | IIF(3<4,'C','D')
3 | IIF(5<1,'E','F')
Query:
SELECT ID, Eval(Formula)
Output:
1 | A
2 | C
3 | F
With Dynamic SQL, but REALLY not recommended. Just in case you REALLY have to...
Declare #YourTable table (ID int,Formula varchar(100))
Insert Into #YourTable values
(1,'IIF(2<3,''A'',''B'')'),
(2,'IIF(3<4,''C'',''D'')'),
(3,'IIF(5<1,''E'',''F'')')
Declare #SQL varchar(max) = '>>>'
Select #SQL = Replace(#SQL + concat(' Union All Select ID=',ID,',Value=',Formula),'>>> Union All','')
From #YourTable
Exec (#SQL)
Returns
ID Value
1 A
2 C
3 F

SQL Column Names from a Excel Sheet

Im using SSMS 2014 and SQL Server 2014. I need to change the column names at the end of a query result by using a excel file or table with the data.
After some SELECT statements and stuff i get a table with data for example
+---------+---------+------+
| Col1 | Col2 | Col3 |
+---------+---------+------+
| Value 1 | Value 2 | 123 |
| Value 2 | Value 2 | 456 |
| Value 3 | Value 3 | 789 |
+---------+---------+------+
And the table or excelfile
+----+---------+-----------+-----------+
| ID | ColName | Language | Addition |
+----+---------+-----------+-----------+
| 1 | Col1 | D | 123 |
| 2 | Col2 | D | 456 |
| 3 | Col3 | D | 789 |
| 4 | Col1 | E | 123 |
| 5 | Col2 | E | 456 |
| 6 | Col3 | E | 789 |
+----+---------+-----------+-----------+
What i try to do is to get the addition value of each column and add it to the column name. It should only add the values with the specific language. #setLang = 'D'
Col1 + Addition
Col2 + Addition
Col3 + Addition
+-------------+-------------+---------+
| Col1 123 | Col2 456 | Col3789 |
+-------------+-------------+---------+
| Value 1 | Value 2 | 123 |
| Value 2 | Value 2 | 456 |
| Value 3 | Value 3 | 789 |
+-------------+-------------+---------+
I tried it over Information_Schema.Columns and filter with where table = 'resultTable' and Column_name = #cName. Maybe i need a loop to get each columnname.
Thanks for reading and trying to help me.
Give this a go - it uses a table, not an excel file (but that seems to be an option in your question). I have made some temporary tables and filled them with your values, but you will obviously not need to do this. You will need to replace out the references to the tempdb with the name of the database where your tables are kept and the temp tables #Original and #ExcelInfo with your table names.
I have also used a temp table to add an 'Id IDENTITY(1,1)` Column to the table holding your original data. This is needed to keep the unpivot in check; if you can modify your table to include an Id, that will make things easier, but if not, you can insert into a temp table as I have done.
The script is shorter than it looks - the whole first bit is just setting up the example; the real answer starts at the line that declares your language variable.
/*
The script between the first two dividing lines of dashes is just used to set up the example. The bit you want is from
the "-- Test Variables --" line.
*/
-----------------------------------------------------------------------------------------------------------------------
IF OBJECT_ID('tempdb..#Original') IS NOT NULL DROP TABLE #Original
IF OBJECT_ID('tempdb..#ExcelInfo') IS NOT NULL DROP TABLE #ExcelInfo
CREATE TABLE #Original
( Col1 VARCHAR(50)
,Col2 VARCHAR(50)
,Col3 VARCHAR(50))
CREATE TABLE #ExcelInfo
( Id INT IDENTITY(1,1) NOT NULL
,ColName VARCHAR(50) NOT NULL
,[Language] CHAR(1) NOT NULL
,Addition INT NOT NULL)
INSERT #Original
SELECT *
FROM
( SELECT 'Value 1' AS Col1,'Value 2' AS Col2 ,123 AS Col3
UNION SELECT 'Value 2' ,'Value 2' ,456
UNION SELECT 'Value 3' ,'Value 3' ,789) AS This
ORDER BY Col1
INSERT #ExcelInfo (ColName,[Language],Addition)
SELECT *
FROM
( SELECT 'Col1' AS ColName, 'D' AS [Language], 123 AS Addition
UNION SELECT 'Col2','D',456
UNION SELECT 'Col3','D',789
UNION SELECT 'Col1','E',123
UNION SELECT 'Col2','E',456
UNION SELECT 'Col3','E',789) AS This
ORDER BY [Language], Addition
-----------------------------------------------------------------------------------------------------------------------
-- Test Variables --
DECLARE #SetLang CHAR(1) = 'D'
-----------------------------------------------------------------------------------------------------------------------
-- make the default empty, not null on our dynamic string, so it can be added to
DECLARE #Columns VARCHAR(MAX) = ''
DECLARE #SQL VARCHAR(MAX)
CREATE TABLE #OriginalColumns
( Id INT IDENTITY(1,1)
,Name VARCHAR(50))
CREATE TABLE #BasicResult
(Id INT NOT NULL, Name VARCHAR(50), Value VARCHAR(50))
-- If you can add an id column to your original table, this bit is unecessary - you can use yours in place of this table
CREATE TABLE #Original_WITH_Id
( Id INT IDENTITY(1,1)
,Col1 VARCHAR(50)
,Col2 VARCHAR(50)
,Col3 VARCHAR(50))
INSERT #Original_WITH_Id
SELECT * FROM #Original
-----------------------------------------------------------------------------------------------------------------------
-- List out the columns and put the list in a variable.
INSERT #OriginalColumns
SELECT QUOTENAME(Col.name)
FROM tempdb.sys.columns AS Col
WHERE Col.object_id = OBJECT_ID('tempdb.dbo.#Original_WITH_Id')
-- we're not interested in the identity column at the moment
AND Col.name <> 'Id'
-- keep everything in the same order as they are listed on the table
ORDER BY Col.column_id
SELECT #Columns = #Columns + ',' + Name
FROM #OriginalColumns
-- clip off the leading comma
SELECT #Columns = SUBSTRING(#Columns,2,LEN(#Columns))
-- get a full list of everything, creating our new list of columns as we go, using the Id column to keep a mark on which
-- row each record originally came from
SET #SQL =
'INSERT #BasicResult
SELECT Id, New.Name, Value FROM
(SELECT Id, Name, Value
FROM #Original_WITH_Id
UNPIVOT (Value FOR Name IN (' + #Columns + ')) Unpvt) AS Old
JOIN (SELECT ColName, CONVERT(VARCHAR(50),ColName) + '' '' + CONVERT(VARCHAR(50),Addition) AS Name
FROM #ExcelInfo
WHERE [Language] = ''' + #SetLang + ''') AS New ON Old.Name = New.ColName'
PRINT #SQL
EXEC (#SQL)
-- now update our list of columns to be the new column headings
SET #Columns = ''
SELECT #Columns = #Columns + ',' + QUOTENAME(Name) FROM (SELECT DISTINCT Name FROM #BasicResult) AS Names
SELECT #Columns = SUBSTRING(#Columns,2,LEN(#Columns))
-- pivout our results back out to their original format, but with the new column headings (include the Id if you want)
SET #SQL =
'SELECT /*Id,*/ ' + #Columns + '
FROM
(SELECT Id, Name,Value
FROM #BasicResult) AS Up
PIVOT (MAX(Value) FOR Name IN (' + #Columns + ')) AS Pvt'
PRINT #SQL
EXEC (#SQL)
-- clean up --
DROP TABLE #OriginalColumns
DROP TABLE #BasicResult
Hope that helps! There may be a more efficient way to do this... I'm not sure.
Okay i tried it again but now without the Excelfile. I made a CSV out of the Excelfile and insert it with Bulk to my created Table:
IF NOT EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'CSVTest')
BEGIN
CREATE TABLE _DICTIONARY
( _TableName VARCHAR (20),
_ColumnName VARCHAR (20),
_Language VARCHAR (20),
_FieldShort VARCHAR (50),
_FieldMid VARCHAR (50),
_FieldLong VARCHAR (50)
)
BULK
INSERT _DICTIONARY
FROM 'C:\_DICTIONARY.csv'
WITH
(
FIELDTERMINATOR = ';',
ROWTERMINATOR = '\n'
)
END
After that i rename all Columns by using a Cursor
DECLARE #dic_tableName as nvarchar(50),
#dic_columnName as nvarchar(50),
#db_tableName as nvarchar(50),
#db_columnName as nvarchar(50);
DECLARE C CURSOR FAST_FORWARD FOR
SELECT _TableName, _ColumnName FROM _DICTIONARY
OPEN C;
FETCH NEXT FROM C INTO #dic_tableName, #dic_columnName;
WHILE ##FETCH_STATUS = 0
BEGIN
IF EXISTS(SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = #dic_tableName AND COLUMN_NAME = #dic_columnName)
BEGIN
SET #db_tableName = #dic_tableName + '.' + #dic_columnName
SET #db_columnName = #dic_tableName + '_' + #dic_columnName
EXEC sp_rename #db_tableName, #db_columnName ,'COLUMN'
FETCH NEXT FROM C INTO #dic_tableName, #dic_columnName;
END
ELSE
BEGIN
FETCH NEXT FROM C INTO #dic_tableName, #dic_columnName;
END
END
CLOSE C;
DEALLOCATE C;
Its doing its job.

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