How to declare dynamic parameter from stored procedure into code behind - sql

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

Related

Insert into Temp Table from SQL Dynamic Results

I am trying to insert the result of the sql dynamic into a temp table but i am getting a syntax error. I have researched and i am not able to figure what i am doing wrong here
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName = ISNULL(#ColumnName + ',','') + QUOTENAME([month])
FROM (SELECT DISTINCT [Month] FROM MyTable) AS [Month]
order by [month]
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT Mem_Name, ' + #ColumnName + '
FROM MyTable into MyTest
PIVOT(SUM(Amount)
FOR Month IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
all what i had to do is add this:
' into ##myTempTable
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName = ISNULL(#ColumnName + ',','') + QUOTENAME([month])
FROM (SELECT DISTINCT [Month] FROM MyTable) AS [Month]
order by [month]
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT Mem_Name, ' + #ColumnName + ' into ##myTempTable
FROM MyTable
PIVOT(SUM(Amount)
FOR Month IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery

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

Changing my statement to work in a SQL function

I wanted to create a view using my SQL statement but found out you can't use declare in a view. So I was trying to create a function so my view could just call it
This is the SQL statement
--Declare necessary variables
DECLARE #SQLQuery AS NVARCHAR(255)
DECLARE #Pivot AS NVARCHAR(255)
--Get unique values of pivot column
SELECT #Pivot = COALESCE(#Pivot + ',','') + QUOTENAME(Stage)
FROM
(SELECT DISTINCT Stage
FROM [dbo].[F_Work_Order_Summary]) AS Pivot
--Create the dynamic query with all the values for
--pivot column at runtime
SET #SQLQuery = N'SELECT *
FROM [dbo].[F_Work_Order_Summary]
PIVOT(SUM(Time_In_Stage)
FOR Stage IN (' + #Pivot + ')) AS P'
--Execute dynamic query
EXEC sp_executesql #SQLQuery
Was wonder if anyone could help or knows a better way to use this statement with a view.
Thanks

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;

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