Select distinct from temp table - sql

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;

Related

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.

Error converting data type varchar to numeric dynamic pivot

I am getting an error described in the title where my code looks like this:
declare
#cols numeric(10,0),
#sql numeric(10,0)
select #cols = isnull(#cols + ', ', '') + '[' + T.AmountPayd + ']' from (select distinct AmountPayd from t1) as T
select #sql = '
select *
from t1 as T
pivot
(
sum(T.AmountPayd) for T.Customer in (' + #cols + ')
) as P'
exec sp_executesql #sql = #sql
The error occurs at this line:
select #cols = isnull(#cols + ', ', '') + '[' + T.AmountPayd + ']' from (select distinct AmountPayd from t1) as T
In my table AmountPayd is declared as numeric data type.
The error I get is:
Msg 8114, Level 16, State 5, Line 108 Error converting data type
varchar to numeric.
You've declared #cols as numeric(10,0), but you're trying to assign text to it.
Probably need to declare it as nvarchar(max).
P.s.
by concatenating AmountPayd you're suppose to get a list of customers?
declare
--#cols numeric(10,0),
--#sql numeric(10,0)
#cols varchar(max),
#sql varchar(max)
--Here you are setting #cols to a concatenated list of the amounts in your table
--The problem is you are trying to concat a decimal or integer into a string without casting it
--This is the same as doing 'A' + 1 and wanting to get A1. You first have to cast it.
--Notice the CAST(T.AmountPayd AS VARCHAR). But cols still needs to be a varchar in your declaration.
select #cols = isnull(#cols + ', ', '') + '[' + CAST(T.AmountPayd AS VARCHAR) + ']' from (select distinct AmountPayd from t1) as T
--Here you are building your dynamic SQL, which is a string which is why #sql must be varchar or nvarchar
select #sql = '
select *
from t1 as T
pivot
(
sum(T.AmountPayd) for T.Customer in (' + #cols + ')
) as P'
exec sp_executesql #sql = #sql
You've almost copied this example line for line, you just missed the declaration of your variables.
http://sqlhints.com/2014/03/18/dynamic-pivot-in-sql-server/

Return SELECT query result as a CSV string

I have the following Sql Server 2016 SELECT statement that returns only 1 row:
SELECT TOP 1 * FROM tempdb.dbo.IMTD
How can I concatenate the values as a comma delimited string? NOTE: the column names of this temporary table are unknown as they can variate.
Thank you.
Something like this perhaps:
-- Sample data
DECLARE #someTable TABLE (SomeID int identity, SomeTxt varchar(100));
INSERT #someTable VALUES ('row1'),('row2'),('row3');
-- Solution
SELECT ConcatinatedString =
STUFF
((
SELECT ','+SomeTxt
FROM #someTable
FOR XML PATH(''), TYPE
).value('.','varchar(100)'),1,1,'');
You can use Dynamic query as below:
DECLARE #COLS VARCHAR(MAX) = ''
SELECT #COLS = #COLS + ',' + COLUMN_NAME
FROM tempdb.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '#table[_]%' -- Dynamic Table (here, Temporary table)
DECLARE #COLNAMES VARCHAR(MAX) = REPLACE(STUFF(#COLS, 1, 1, ''), ',', '+ '','' +')
Declare #cmd varchar(max) = 'Select ' + #COLNAMES + ' as CSVCol from #table'
-- will generate
-- Select Column1+ ',' +Column2+ ',' +Column3 as CSVCol from #table
EXEC (#cmd)
Another solution you can try is this.
SELECT LTRIM(RTRIM(<ColumnName1>)) + ',',
LTRIM(RTRIM(<ColumnName2>)) + ',',
...
LTRIM(RTRIM(<ColumnNamen>)) + ','
FROM tempdb.dbo.IMTD
If you only want one row keep that top 1 In there like
SELECT TOP 1
LTRIM(RTRIM(<ColumnName1>)) + ',',
LTRIM(RTRIM(<ColumnName2>)) + ',',
...
LTRIM(RTRIM(<ColumnNamen>)) + ','
FROM tempdb.dbo.IMTD
The LTRIM and RTRIM will remove any white space and this should allow you to copy and paste the result set anywhere you may need it. You will need to do this for each columnname.
You can use the query below to get the column names from your temp table.
DECLARE #ColumnNames NVARCHAR(MAX)
SELECT
#ColumnNames= COALESCE(#ColumnNames +',','')+COLUMN_NAME
FROM
TempDB.INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = '#TempTableName'

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

Transpose/Pivot Table without knowing the number or names of attributes

I want to transpose an SQL table from a row into a column of results. The statement will only return one record however at the time of running the query I will not know the names of attributes in the table. All the query will know is the table and the ID column to return the relevant record.
i.e. I would like to return this as a column of results:
SELECT * FROM ExampleTable WHERE (PKCol = 'XYZ');
That is the only information I will know at the time of running the query in SQL Server 2012.
Thanks
You should retrieve column names from sys.columns system view, concat them in cusror and use UNPIVOT.
Something like this:
DECLARE #columns AS NVARCHAR(MAX) = '', #columns_char AS NVARCHAR(MAX) = '', #query AS NVARCHAR(MAX)
SELECT #columns += ',' + c.name, #columns_char += ',CAST(' + c.name + ' AS VARCHAR(255)) AS ' + c.name FROM sys.columns AS c WHERE c.object_id = OBJECT_ID(N'Your Table Name')
SELECT #columns = STUFF(#columns, 1, 1, ''), #columns_char = STUFF(#columns_char, 1, 1, '')
SELECT #columns, #columns_char
SET #query =
N'SELECT
column_name,
col
FROM
(
SELECT ' + #columns_char + ' FROM ' + Your_table_name + N' AS t
WHERE t.id = ' + Your Id + N'
) AS sel
UNPIVOT
(
col FOR column_name IN(' + #columns + ')
) AS upt';
EXEC sp_executesql #query