sql query code dont run dynamic - sql

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

Related

Column Matching Data featch in SQL

DECLARE #ompid NVARCHAR(max)
DECLARE #Names VARCHAR(max)
SELECT #Names = COALESCE(#Names + ') as ' + Variable_Name + ' ,AVG(', 'AVG(') + Variable_Name
FROM charttest
WHERE ompid = 125
DECLARE #lastcol NVARCHAR(100) = (
SELECT TOP 1 (Variable_Name)
FROM charttest
WHERE ompid = 125
ORDER BY Variable_Name ASC
)
DECLARE #Names2 NVARCHAR(500) = #Names + ') as ' + #lastcol + ''
DECLARE #sql NVARCHAR(500)
SET #sql = 'SELECT ' + #Names2 + ' FROM ompvaribles'
EXEC (#sql)
This is my sql query i had show second table avg but not getting second table records.
I'm not sure what is actually not working with your query (I'm assuming you get an error), but in order to execute the dynamic query you've build you need to use:
exec sp_executesql #sql

Make multiple columns into one column in 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;

How to declare dynamic parameter from stored procedure into code behind

I have one stored procedure. The parameter in the stored procedure is dynamic.
I don't know to declare and use the parameter in code behind(VB.net) of my page.
This is the stored procedure:
CREATE PROCEDURE [dbo].[Gdata2]
--#employeeID varchar(10),
--#employeeCostCenterCode varchar(20)
AS
BEGIN
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','') + QUOTENAME(Product)
FROM (SELECT DISTINCT Product FROM V_SBR_Product) AS Products
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery = N'SELECT Quarter, ' + #ColumnName +
'FROM V_SBR_Product ' +
'PIVOT(COUNT(Total) FOR Product IN (' + #ColumnName +
')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
END

Dynamic SQL Stored Procedure 2nd result set

I am working on a request to display selected test results from two tables via SSRS. I have developed the dynamic SQL to accomplish this but got stuck when running the stored procedure, as I only receive the first result set.
This stored procedure first queries a tag name table that is used to build columns for the second query... which retrieves the actual desired data. The SP returns the column names but does not return the needed second result set.
I realize this is an ugly solution but our IT group had no input into original database design, so now we're trying to do what we can to help.
Code:
DECLARE #cols as NVARCHAR(MAX), #query1 as NVARCHAR(MAX), #query2 as NVARCHAR(MAX),
#FLOATTABLE NVARCHAR(MAX), #TAGTABLE NVARCHAR(MAX),#startdate as NVARCHAR(MAX),
#ENDDATE AS NVARCHAR(MAX), #results as NVARCHAR(MAX)
set #FLOATTABLE = 'dbo.TRW_TESTER_FLOATTABLE' --for testing purposes only
set #tagtable = 'dbo.TRW_TESTER_TAGTABLE' --for testing purposes only
Set #startdate='2013-12-05' -- for testing purposes only
Set #enddate='2013-12-31' -- for tesying purposes only
set #query2 = 'SELECT STUFF((SELECT DISTINCT '','' +
QUOTENAME(CONVERT(VARCHAR,TagName),'
+ '''"'') FROM ' + #TAGTABLE + ' FOR XML PATH ('''')),1,1,'''')'
EXECUTE sp_executeSQL #query2, #Cols OUTPUT
Set #query1 = 'SELECT DISTINCT DateAndTime, Millitm, ' + #cols + ' FROM ( select
T.DateAndTime, T.Millitm, N.TagName, T.Val from ' + #FLOATTABLE + ' T LEFT JOIN ' +
#TAGTABLE + ' N ON T.TagIndex=N.TagIndex WHERE T.DateAndTime Between '''+ #startdate +
''' AND '''+ #enddate +''') x PIVOT (MAX(Val) for TagName IN (' + #cols + ')) p'
EXECUTE sp_executeSQL #query1, #results OUTPUT

How to form a table name from concatenating strings in Select Statement in SQL 2012

I want to achieve this -
SELECT * FROM A1234
I have the the ID 1234 saved in another table called Aliases which has two columns Alias,ID with one record like this.
Alias = TestTable, ID = 1234
So I am trying something like this
SELECT * FROM ('A'+ (SELECT ID FROM Aliases WHERE Alias = 'TestTable'))
Any help would be appreciated
You should use dynamic sql.
DECLARE #Q VARCHAR(MAX),#ID INT
SET #ID=(Select DISTINCT ID from Aliases where Alias = 'TestTable') -- CHECK TO RETURN JUST ON RESULT
SET #Q='SELECT * FROM A'+CAST(#ID AS VARCHAR(10))
EXEC(#Q)
You need dynamic SQL for this.
DECLARE #sql NVARCHAR(MAX);
SELECT TOP (1) #sql = N'SELECT * FROM A' + RTRIM(ID) + ';'
FROM dbo.Aliases WHERE Alias = 'TestTable';
EXEC sp_executesql #sql;
To build a set of statements that selects all of them, you can say:
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'';
SELECT #sql = #sql + N'
SELECT *, ''A' + RTRIM(ID) + ''' FROM A' + RTRIM(ID) + ';'
FROM dbo.Aliases;
PRINT #sql;
-- EXEC sp_executesql #sql;