Make multiple columns into one column in sql - sql

I have a table Employee which have several fields like FirstName,LastName,Email,....... . So what i want to do is that in my case selection of column is dynamic
Declare #columnNeeded nvarchar(max)
Example one
Set #columnNeeded = 'FirstName,Email'
Select #columnNeeded from Employee
Example Two
Set #columnNeeded = 'FirstName,LastName'
Select #columnNeeded from Employee
This is pretty simple , now what i want is that regardless of what column will be in result set i need all column selected in one column as comma seperated string . I saw Group_Concat() in mysql but don't know how to do this in sql .So is this possible ?

You can do this with dynamic SQL:
declare #sql nvarchar(max) = 'select #columns from Employee';
declare #columnNeeded nvarchar(max) = 'FirstName,Email';
set #sql = replace(#sql, '#columns', #columnNeeded);
exec sp_executesql #sql;
EDIT:
If you want them as one column, you could do:
declare #sql nvarchar(max) = 'select #columns from Employee';
declare #columnNeeded nvarchar(max) = 'FirstName,Email';
set #sql = replace(replace(#sql, '#columns', #columnNeeded), ',', '+'',''+');
exec sp_executesql #sql;
To type-safe you would cast the column values:
declare #tmp nvarchar(4000) = 'cast(' +
replace(#columnNeeded, ',', ', nvarchar(4000)), cast(') +
', nvarchar(4000))'
set #sql = replace(replace(#sql, '#columns', #columnNeeded), ',', '+'',''+');
If this works as expected, it adds cast(<col> as nvarchar(4000)) to each of the columns in the list.

You have to use Dynamic SQL. Since you have different Data types in your table you may have to convert the columns to Varchar to concatenate the result into single column.
DECLARE #sql NVARCHAR(max),
#cols NVARCHAR(max) ='FirstName,Email'
SELECT #cols = 'convert(varchar(100),'
+ Replace(#cols+')+', ',', ')+'',''+convert(varchar(100),')
SELECT #cols = LEFT(#cols, Len(#cols) - 1)
SET #sql ='select ' + #cols + ' from Employee '
--print #sql
EXEC Sp_executesql #sql;
Working Example :
CREATE TABLE #test1([Key] INT,ID INT,Value VARCHAR(2))
INSERT #test1
VALUES (1,1,'C' ),(2,1,'C' ),(3,1,'I' )
DECLARE #sql NVARCHAR(max),
#cols NVARCHAR(max) ='ID,Value'
SELECT #cols = 'convert(varchar(100),'
+ Replace(#cols+')+', ',', ')+'',''+convert(varchar(100),')
SELECT #cols = LEFT(#cols, Len(#cols) - 1)
SET #sql ='select ' + #cols + ' from #test1 '
EXEC Sp_executesql #sql;

Related

Variable in SQL query syntax

I want to make a simple SQL query like:
SELECT * FROM table WHERE $variable_2 = $variable_1
instead of a default one:
SELECT * FROM table WHERE column_name = $variable_1
It seems like first example doesn't work at all. Is it even possible to modify SQL query syntax in such way?
as this reference answer for:
in link:
Use Variable as SQL column Name in query
answer1:
declare #ColumnName varchar(50)
declare #sql nvarchar(max)
set #ColumnName = 'SalesData_' + convert(varchar(2),datepart(dd,getdate()))
set #sql = 'select ' + #ColumnName + ' from SalesTable'
print #sql
EXEC sp_sqlexec #sql
answer 2:
declare #ColumnName varchar(50)
declare #sql nvarchar(max)
set #ColumnName = 'SalesData_' + convert(varchar(2),datepart(dd,getdate()))
set #sql = 'select ' + #ColumnName + ' from yourschema.SalesTable'
print #sql

Passing a variable out of a SQL query

Is it possible to pass a variable out of a SQL query?
I am building up the initial query using a variable. I have added a simplified subset of my query below.
Thanks
declare #query Nvarchar(max)
declare #ColumnName Nvarchar(max)
set #ColumnName = 'MyColumn'
SET #query = 'Select ' + #ColumnName + ' from [MyTable] WHERE [MyCondition]'
EXECUTE sp_executesql #query
Can I return this result as a variable to pass to another query?
Yes. You use an output parameter:
declare #query Nvarchar(max);
declare #ColumnName Nvarchar(max);
declare #outval <type>; -- whatever type
set #ColumnName = 'MyColumn'
set #query = 'Select #outval =' + #ColumnName + ' from [MyTable] where [MyCondition]';
execut sp_executesql #query,
N'#outval <type> output',
#outval = #outval output;
Store the results in table variable and then convert it into XML.
Declare #xml XML
declare #query Nvarchar(max)
declare #ColumnName Nvarchar(max)
set #ColumnName = 'MyColumn'
declare #Table as TABLE(
MyColumn varchar(Max)-- Your Column datatype
)
SET #query = 'Select ' + #ColumnName + ' from [MyTable] WHERE [MyCondition]'
INSERT INTO #Table
EXECUTE sp_executesql #query
select #xml=MyColumn from #Table for XML PATH('')
How you want to pass returned result to other query?
What i can think of create a function return a table and call that function on other query:
CREATE FUNCTION test (#id int)
RETURNS #testTable TABLE(id int)
AS
begin
insert into #testTable select id from #your_table where id = #id
return
end
This will return a table you can check using :
select * from test(2); --will give you a table
If you want to use in a query:
`select * from #second_table where id in (select * from test2(#id parameter))` --- will filter query by id returned by function.

sql query code dont run dynamic

i want have the layout of pivot table with on top period YYYYMM in dynamic table.
show sum of consumption per month show 1 year.
but when i tried put the data (period (201801,201802...)) don't work with PERIOD table on dynamic ?!!
i don't know if im doing something wrong on the report ...can anyone help withit ?
The query without be in dynamic and work but when I tried to change to dynamic I can't make it work.
DECLARE #ColumnNames NVARCHAR(MAX) = ' '
DECLARE #SQL NVARCHAR (MAX) = ' '
SELECT #ColumnNames += QUOTENAME(Period) + ','
FROM [STOKVIS LIVE].[dbo].[SR_CONS_Consumption1year]
SET #ColumnNames = LEFT (#ColumnNames,LEN(#ColumnNames)-1)
SET #SQL =
SELECT [No_] ,[Group],[Lakeview],[Name],[class.],[Stock], [Period]
FROM [STOKVIS LIVE].[dbo].[SR_CONS_Consumption1year]
PIVOT (
SUM ([Qty])
FOR [Period]
IN( ' + #ColumnNames + ')
)
as pivortable
You are executing 2 queries that require dynamic syntax - I've not tested but I think you could try something like this:
--Declare Variables
DECLARE #ColumnNames NVARCHAR(MAX) = NULL
DECLARE #SQL NVARCHAR(MAX)
-- First dynamic query
SET #SQL = N'
SELECT #ColumnNames += QUOTENAME(Period) + '',''
FROM [STOKVIS LIVE].[dbo].[SR_CONS_Consumption1year] ;';
--Execute dynamic query
EXEC sp_executesql #sql, N'#ColumnNames NVARCHAR(MAX)', #ColumnNames;
SET #ColumnNames = LEFT (#ColumnNames,LEN(#ColumnNames)-1)
--second dynamic query
SET #SQL = N'
SELECT [No_] ,[Group],[Lakeview],[Name],[class.],[Stock], [Period]
FROM [STOKVIS LIVE].[dbo].[SR_CONS_Consumption1year]
PIVOT (
SUM ([Qty])
FOR [Period]
IN( ' + #ColumnNames + ')
)
AS PivotTable ;';
EXEC sp_executesql #sql, N'#ColumnNames NVARCHAR(MAX) OUT', #ColumnNames OUT;
SELECT #TransType
EDIT
Added OUT in the past EXEC to identify they are output variables so you can use SELECT #TransType to get the result

Create table as value from select statement

How to create table from select statement?
For example, I have format table as below:
FormatID Label
1 ID
2 Name
3 DOB
So I want to create new table with column name ID, Name, DOB.
Any pointer would be appreciated.
You could try like this:
-- build the SQL query
declare #sql nvarchar(max) = ''
select #sql = #sql + '[' + Label + '] nvarchar(255), ' from Format order by FormatID
select #sql = 'create table [MyTable] (' + #sql + ')'
-- create the table
EXECUTE sp_executesql #sql
go
-- lets see if the table actually got created
sp_help MyTable
go
you can do ...
declare #sql as varchar( max) ='';
declare #cln as varchar( max) ='';
select #cln =( SELECT Label + ' nvarchar(50) , ' from format FOR XML PATH('')
);
set #sql = 'create table tablename ( '+ #cln + ' );
sp_executesql #sql ;
#sandeep rawat. Thanks, I modified some and i can now got it ;)
declare #sql as nvarchar(max) ='';
declare #cln as nvarchar(max) ='';
select #cln =(SELECT REPLACE(label, ' ', '') + ' nvarchar(50),' from format FOR XML PATH('') );
set #cln = substring(#cln,1,len(#cln)-1)
set #sql = 'create table new_table ('+ #cln + ')';
print #sql
print len(#sql)
exec sp_executesql #sql ;
This will help you
select FormatID,Label into New_table_Name from Table_Name where 1=0;
There was little misunderstanding.
Hope it will help you.
create table #Tbl_Format
(FormatId int identity(1,1),
Lebel Varchar(64)
)
insert into #Tbl_Format
values('Id'),('Name'),('DOB')
Declare #Query nvarchar(512)
SET #Query= (SELECT ', ' + Lebel+' NVARCHAR(64)'
FROM #Tbl_Format
FOR XML PATH(''))
SET #Query='CREATE TABLE Table_Name ('+Substring(#Query,2,LEN(#Query))+')'
EXEC (#Query)
Thanks

Must declare the scalar variable with Table-Valued Parameters and Stored Procedure

Could someone explain why the following gives me "Must declare the scalar variable #facilities." but works fine if I were to use VARCHAR instead of my created type? How can I fix this?
TIA
--CREATE TYPE integer_list AS TABLE (n int NOT NULL PRIMARY KEY)
--DROP PROCEDURE spTestTVP
CREATE PROCEDURE spTestTVP (
#facilities integer_list READONLY
--#facilities varchar(100)
)
AS
DECLARE #sql nvarchar(4000)
SET #sql = 'SELECT * FROM TestTable'
SET #sql = #sql + ' WHERE 1=1 '
IF #facilities IS NOT NULL
SET #sql = #sql + ' AND (FacilityNo IN (' + #facilities + ') OR FacilityNo IS NULL)'
EXEC sp_executesql #sql
DECLARE #items VARCHAR(MAX)
SELECT#items = COALESCE(#items+',' ,'') + n
FROM #facilities
DECLARE #sql nvarchar(4000)
SET #sql = 'SELECT * FROM TestTable'
SET #sql = #sql + ' WHERE 1=1 '
IF #facilities IS NOT NULL
SET #sql = #sql + ' AND (FacilityNo IN (' + #items + ') OR FacilityNo IS NULL)'
EXEC sp_executesql #sql
or not dynamic as follows:
SELECT t.* FROM TestTable as t
left outer join
#facilities as f
on
f.n = t.FacilityNo
where
t.FacilityNo is null
or
f.n is not null
When you are concatenating things in a dynamicSQl statment all pieces that build the statement must be either varchar or nvarchar. That is a limit of SQL.
On the other hand you don't need dynamic sql since you have created a table.
SELECT * FROM TestTable t
LEFT join #facilities f on f.n = t.facilityNO