SQL Concatenate ids into a specific order - sql

I have the following query which works great, it puts all my ids in a comma separated list.
DECLARE #tmp nvarchar(max)
SET #tmp = ''
SELECT #tmp = #tmp + cast(id as nvarchar(max)) + ', '
FROM dbo.property
I want to put my ids in alphabetical order but when I add order by p.Name it only gives my the top one result.
How can I adapt my query to accomplish this?

This really doesn't work?
DECLARE #tmp nvarchar(max);
SET #tmp = '';
SELECT #tmp = #tmp + cast(id as nvarchar(max)) + ', '
FROM dbo.property p
order by p.name;
In any case, you can use this method:
select #tmp = stuff((select ', ', cast(id as nvarchar(max))
from db.property p
order by p.name
for xml path ('')
), 1, 2, '');

The solution:
SELECT (cast(ID as nvarchar(max)) + ', ') AS [text()]
FROM dbo.property
ORDER BY ID
FOR XML PATH ('')

Related

Select distinct from temp table

I am trying to select distinct values from my temporary table column into varchar variable in sql server.
i tried following but it doesnt work.
DECLARE #GuidPrimaryTableSpace NVARCHAR(MAX);
SET #GuidPrimaryTableSpace = '';
SELECT DISTINCT
#GuidPrimaryTableSpace = #GuidPrimaryTableSpace+DeleteGuidStatement+';'+CHAR(13)+CHAR(10)
FROM ##Purge_GuidForeignKeyTablePurgeStatements;
Please Help!
I would recommend using the XML approach for string concatenation:
SELECT #GuidPrimaryTableSpace =
STUFF((SELECT DISTINCT ';' + CHAR(13) + CHAR(10) + DeleteGuidStatement
FROM ##Purge_GuidForeignKeyTablePurgeStatements
FOR XML PATH (''), TYPE
).value('.', 'NVARCHAR(MAX)'
), 1, 3, ''
)
FROM ##Purge_GuidForeignKeyTablePurgeStatements;
You can use your method if you use a subquery:
DECLARE #GuidPrimaryTableSpace NVARCHAR(MAX);
SET #GuidPrimaryTableSpace = '';
SELECT #GuidPrimaryTableSpace = #GuidPrimaryTableSpace + DeleteGuidStatement + ';' + CHAR(13) + CHAR(10)
FROM (SELECT DISTINCT DeleteGuidStatement
FROM ##Purge_GuidForeignKeyTablePurgeStatements
) t;

Inserting Different Value IN a Table

Well I'm Creating a Table Based on Result Set Of Databases On Server which contain Multiple Databases.
My table will Create a list of column which contain Database_Name
FOR EG:
DECLARE #strt INT,#End INT,#Database NVARCHAR(20), #ColumnDeclaration VARCHAR(2000),#SqlSelect NVARCHAR(MAX),#column_Name NVARCHAR(255)
SELECT * INTO #T FROM SYS.DATABASES
ORDER BY NAME
SELECT #ColumnDeclaration=STUFF(( SELECT ', ' + Name + ' NVARCHAR(255)'
FROM #T
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(max)'), 1, 1, '')
SET #SqlSelect=' CREATE TABLE Temp_Comp (' + #ColumnDeclaration + ');'
PRINT #SqlSelect
EXEC (#SqlSelect)
SELECT * FROM Temp_Comp
I wan't Insert the Data INTO Temp_Comp Table a specific Value from
the database whose Name will be in Temp_comp Table
Not sure what are you trying to achieve, but I assume that you want something like:
DECLARE #strt INT,#End INT,#Database NVARCHAR(20), #ColumnDeclaration NVARCHAR(MAX),#SqlSelect NVARCHAR(MAX),#column_Name NVARCHAR(255)
SELECT * INTO #T
FROM SYS.DATABASES
ORDER BY NAME;
SELECT #ColumnDeclaration=STUFF(( SELECT ', ' + QUOTENAME(Name) + ' NVARCHAR(255)'
FROM #T
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(max)'), 1, 1, '');
SET #SqlSelect=' CREATE TABLE Temp_Comp (col_desc NVARCHAR(200), ' + #ColumnDeclaration + ');';
SELECT #SqlSelect;
EXEC (#SqlSelect);
SET #SQLSelect = ' INSERT INTO Temp_Comp(col_desc, ' + REPLACE(#ColumnDeclaration, 'NVARCHAR(255)', '') + ')' +
' SELECT col,'+ REPLACE(#ColumnDeclaration, 'NVARCHAR(255)', '') +' FROM (' +
' SELECT name, sub.* FROM sys.databases' +
' OUTER APPLY (SELECT ''database_id'', CAST(database_id AS NVARCHAR(MAX)) UNION ALL SELECT ''compatibility_level'', CAST(compatibility_level AS NVARCHAR(MAX)) ) sub(col, val)) src' +
' PIVOT (MAX(val) FOR name IN ('+ REPLACE(#ColumnDeclaration, 'NVARCHAR(255)', '') +') ) piv';
SELECT #SQLSelect;
EXEC (#SQLSelect);
DBFiddle
Result:
In order to INSERT you could use dynamic PIVOT. To add more values just extend OUTER APPLY part.
Keep in mind that you've defined columns as ' NVARCHAR(255)' so you may need to convert values before insert.

SQL create distinct comma separated lists

I have a stored procedures that accepts a comma separated list, then makes copies of that list with quoted strings and brackets, then uses those in a dynamic sql statement to build a pivot table with flexible number of columns.
My problem is that sometimes my users submit a list with duplicates, and that makes the pivot query fail. So I want to somehow select distinct from my comma separated strings.
Here's how I manipulate the initial string:
Declare #data varchar(max) = '150593, 150593, 150603, 150578, 150604'
Declare #bracketed varchar(max) = ''
Declare #quoted varchar(max) = ''
select #bracketed = #bracketed + quotename(rtrim(ltrim(Value))) + ', ',
#quoted = #quoted + quotename(rtrim(ltrim(Value)), '''') + ', '
from [dbo].[fnSplitStringAsTable](#data, ',')
Select #bracketed = LEFT(#bracketed, len(#bracketed) - 1),
#quoted = LEFT(#quoted, len(#quoted) - 1)
I'm thinking I should be able to add DISTINCT somewhere in this query,
but I can't make it work. How can I select distinct from comma separated lists?
as an alternative solution you can dedupe in xml and convert back to varchar
Declare #data varchar(max) = '150593, 150593, 150603, 150578, 150604'
set #data= (select '''' + cast(cast('<d>'+replace(#data, ', ',',</d><d>')+'</d>' as xml).query('distinct-values(/d)') as varchar) +'''')
select #data
I guess we can add in distinct after you make the table, like this:
select #bracketed = #bracketed + quotename(rtrim(ltrim(Value))) + ', ',
#quoted = #quoted + quotename(rtrim(ltrim(Value)), '''') + ', '
from (
SELECT DISTINCT Value FROM [dbo].[fnSplitStringAsTable](#data, ',')
) T
If this fails try this:
select #bracketed = #bracketed + quotename(Value) + ', ',
#quoted = #quoted + quotename(Value), '''') + ', '
from (
SELECT DISTINCT RTRIM(LTRIM(Value)) AS Value FROM [dbo].[fnSplitStringAsTable](#data, ',')
) T
With a little dynamic sql, you can select distinct values from your string variable into a table variable, and then put those values back into the original variable:
declare #data varchar(max) = '150593, 150593, 150603, 150578, 150604'
declare #table table(data varchar(10))
set #data = 'select distinct value from (values (''' +
replace(#data,', ','''),(''') + ''')) as v(value)'
insert into #table
exec(#data)
set #data = ''
select #data = #data + data +
case row_number() over(order by data desc)
when 1 then ''
else ','
end
from #table
order by data asc
select #data

How to get all records on the basis of Search String In sql

I want to fetch all the records on the basis of Search string
E.G.
Column name: FileName
MasterRoomTwo.jpg
BedRoom.png
MasterbedRoom.gif
and in simple scenario I can use
Declare #FileName nvarchar(60) = NULL
set #FileName = '.jpg'
SELECT *
FROM JobAttachment
WHERE AND Tags LIKE '%' + ISNULL(#FileName ,FileName ) + '%'
ORDER BY updated DESC
but in my case I will get like
set #FileName = '.jpg,.Png,gif'
So how to make query like this?
Any help will be appreciated.
Thanks
Try this. Split the input string and use charindex
SELECT 'MasterRoomTwo.jpg' a INTO #temp UNION
SELECT 'BedRoom.png' UNION
SELECT 'MasterbedRoom.gif'
DECLARE #FileName NVARCHAR(60)
SET #FileName = '.jpg,.Png,gif'
SELECT *
FROM #temp
JOIN (SELECT Rtrim(Ltrim(Split.a.value('.', 'VARCHAR(100)'))) fs
FROM (SELECT Cast ('<M>' + Replace(#FileName, ',', '</M><M>')
+ '</M>' AS XML) AS Data) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)) ad
on Charindex(fs, a) > 0
Try this :
SELECT *
FROM JobAttachment a
JOIN (SELECT t1.nod.value('.', 'varchar(50)') tags
FROM (SELECT Cast('<N>.'
+ Replace(Replace(#FileName, '.', ''), ',', '</N><N>.')
+ '</N>' AS XML) AS format) t
CROSS APPLY format.nodes('/N') AS t1(nod)
WHERE t1.nod.value('.', 'varchar(50)') <> '.') fileformat
ON a.tag LIKE ( '%' + fileformat.tags + '%' )
You can create dynamic condition as
Declare #FileName nvarchar(60) = NULL
set #FileName = '.jpg,.Png,gif'
--append a comma to the string to get correct results with empty strings
--or strings with a single value (no commas)
SET #FileName = #FileName + ',';
declare #x XML
declare #FileSearch nvarchar(max)
select #x = cast( '<F>' + replace ( #FileName,',','</F><F>') + '</F>' as xml)
select #FileSearch = stuff( isnull(#FileSearch , '') +
' OR FileName Like ''%'+ isnull(t.value('.','nvarchar(60)'),'')
+'%''' ,1,3,'')
from #x.nodes('/F') as x(t)
And then create dynamic query to get desired results:
set #sql = 'select * from test where ' -- entire query goes here
+ #FileSearch
exec sp_executesql #sql
DEMO

Comma separated column value from Temporary Table

I am inserting select statement result to Temporary table. I want its one column value comma separated, so I tried following but it is not working.
SELECT #IdList = COALESCE(#IdList+',' ,'') + s.Id
FROM (SELECT Id FROM #_TempStudentTable) as s
I have checked data in #_TempStudentTable, it is having data. But when i try to display IdList, it returns NULL.
Help me. I don't know what's the problem.
Try this :
DECLARE #IdList VARCHAR(MAX)
SELECT #IdList = COALESCE(#IdList + ',','') + CAST(Id AS VARCHAR(100))
FROM #_TempStudentTable
SELECT #IdList
You can get it without variable also using XML like below
SELECT STUFF(( SELECT ',' + CAST(Id AS VARCHAR(10))
FROM #_TempStudentTable
FOR XML PATH (''))
, 1, 1, '')
In SQL Server, you may use the below query to get a list of comma separated column names/headers:
SELECT STUFF((
SELECT ',' + CAST(name AS VARCHAR(50))
FROM (
SELECT name
FROM tempdb.sys.columns
WHERE [object_id] = OBJECT_ID(N'tempdb..#temptablename')
) k
FOR XML PATH('')
), 1, 1, '')