Pivot with a table variable - sql-server

I'm unable to use a pivot the data of a table variable.
Its giving following error on run-time:
"Must declare the scalar variable #reportData"
I have tried as mentioned below
DECLARE #reportData TABLE
(
PERSONID NUMERIC(6,0),
personname VARCHAR(100),
bu VARCHAR(50),
timeperiod VARCHAR(100),
wfstatus VARCHAR(100)
)
I'm using the below dynamic pivot query
declare #query nvarchar(max)
set #query=N'SELECT PERSONID,PERSONNAME,BU,wfstatus,'+#datelist+'
from(
SELECT PERSONID,PERSONNAME,BU,wfstatus,timeperiod
FROM
'+#reportData+') AS SOURCETABLE
PIVOT
(group by wfstatus
FOR timeperiod
IN('+#datelist+')
) as pivorttable
select personid,personname,bu,timeperiod,status from pivorttable'
execute(#query);
can some one help me in this?
I need to use only table variable to maintain concurrency issue.!

FROM'+#reportData attempts to add a table variable to a string, which wont work as a table variable is not a string.
Given that you presumably need to populate reportData first you could switch to an explicitly created temp table
create table #reportData
(
PERSONID NUMERIC(6,0)
...
)
Or use a Table Type;
--run once
CREATE TYPE ReportDataType AS TABLE (
PERSONID NUMERIC(6,0),
personname VARCHAR(100)
)
declare #reportData ReportDataType
insert #reportData values
(111, 'bob'),
(222, 'alice')
declare #query nvarchar(max) = N'select * from #T'
exec sp_executesql #query, N'#T ReportDataType readonly', #reportData

Related

Issue with splitting values and passing to a stored procedure

Iam getting the below input parameter values in one of the stored procedure.
#DocKey1, #DocValue1,
#DocKey2, #DocValue2,
#DocKey3, #DocValue3,
#DocKey4, #DocValue4,
#DocKey5, #DocValue5
From this procedure iam calling another procedure to insert each pair of values.
Right now am calling the InsertDocValues stored procedure multiple times to insert each pair.
exec InsertDocValues #DocKey1, #DocValue1
exec InsertDocValues #DocKey2, #DocValue2
exec InsertDocValues #DocKey3, #DocValue3
exec InsertDocValues #DocKey4, #DocValue4
exec InsertDocValues #DocKey5, #DocValue5
Is there anyway i can pass the complete set of values to another procedure as below and then split each pair and insert
eg: #DocKey1, #DocValue1 and #DocKey2, #DocValue2 etc
#DocKey1, #DocValue1, #DocKey2, #DocValue2, #DocKey3, #DocValue3, #DocKey4, #DocValue4, #DocKey5, #DocValue5
Below is the procedure am using now to insert
Create PROCEDURE [dbo].[InsertDocValues]
(
#DocKey varchar(20),
#DocValue nvarchar(20)
)
AS
SET NOCOUNT ON;
BEGIN
INSERT INTO dbo.DocValues(
DocKey,
DocValue
)
VALUES(
#DocKey,
#DocValue
)
End
Please suggest
May be the below code would work for you.
Using user defined table type variable.
CREATE TYPE DocTable AS TABLE
(
DocKey int,
DocValue nvarchar(50)
);
GO
And then use this type to create required variable in first SP and pass the same to your second SP.
DECLARE #DocTable AS DocTable;
INSERT INTO #DocTable
SELECT #DocKey1, #DocValue1 UNION ALL
SELECT #DocKey2, #DocValue2 UNION ALL
SELECT #DocKey3, #DocValue3 UNION ALL
SELECT #DocKey4, #DocValue4 UNION ALL
SELECT #DocKey5, #DocValue5
You can create the above insert query dynamically also. There are so many ways to populate a table. So, use any one as you are getting output from your first SP.
And then call your Second SP.
EXEC [dbo].[InsertDocValues] #DocTable
Changes in second SP would be look like this.
Create PROCEDURE [dbo].[InsertDocValues]
(
#DocTable DocTable READONLY
)
AS
SET NOCOUNT ON;
BEGIN
INSERT INTO dbo.DocValues(
DocKey,
DocValue
)
SELECT
DocKey,
DocValue
FROM #DocTable
END
I'm getting the sense you have a string of pairs (key,value). Perhaps something like this:
Example
Declare #List varchar(max) = 'Key1:Value1,Key2:Value2'
Insert Into dbo.DocValues(DocKey,DocValue )
Select DocKey = left(RetVal,charindex(':',RetVal+':')-1)
,DocVal = stuff(RetVal,1,charindex(':',RetVal+':'),'')
From (
Select RetSeq = row_number() over (Order By (Select null))
,RetVal = ltrim(rtrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(#List,',','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
) A
The Data Inserted would be
DocKey DocVal
Key1 Value1
Key2 Value2

Take results from one stored procedure and send them to another stored procedure

declare #temp table
(
ItemID varchar(100),
)
INSERT INTO #temp (ItemID, Qt)
EXEC A 'LA'
I want to then take the temp table results in field1 (will show field1 and field2) and loop those results using stored procedure B.
Figured I'd provide an example (I was 99% sure my comment was correct but thought I'd double-check.
CREATE PROC dbo.A #x varchar(10) AS SELECT #x FROM (VALUES (1),(1),(1))x(x);
CREATE PROC dbo.B AS SELECT * FROM ##xx;
IF object_id('tempdb..##xx') IS NOT NULL DROP TABLE ##xx;
CREATE TABLE ##xx (col1 varchar(10));
INSERT ##xx EXEC dbo.A 'hi';
EXEC dbo.B;
Results:
col1
------
hi
hi
hi
You could create a User-Defined Table Type, declare a variable as that type (instead of declaring a table variable) and send that over to a procedure which is expecting that type - as a READONLY.
For example:
CREATE TYPE SomeTableType AS TABLE(
[Id] INT,
[Val] VARCHAR(10)
)
Create a procedure that takes this type as a READONLY parameter:
CREATE PROCEDURE p_some_procedure_name
#table SomeTableType READONLY
AS
SELECT * FROM #table;
Now you can declare an instance of your type anywhere (say another procedure), populate it with data and call p_some_procedure_name with it:
DECLARE #temp_table SomeTableType;
INSERT #temp_table(Id, Val) VALUES (1, 'First'), (2, 'Second');
EXEC p_some_procedure_name #temp_table;
If possible (which is often the case), avoid looping.

list of dates to use in a script

Is it possible to define a list of dates (for example: 19122016, 26122016, 01012017, 08012017) which every combinations of dates(like: [19122016, 08012017]) would be selected as 'first_date' and 'secound_date' to perform script?
declare #last_date varchar(10), #previous_date varchar(10), #sql varchar(max);
set #last_date ='20170115';
set #previous_date = '20170108';
set #sql = 'select *
into umkp.dbp.rosk_'+#last_date+'_seg
from umkp.dbp.rosk_'+#previous_date+'_seg'
And as a result would be a list of tabels created.
Create a table, or table-variable to hold the dates pairs. Then use that table to create a select into-statement for each row in the table.
DECLARE #dates TABLE(last_date varchar(10), previous_date varchar(10));
INSERT #dates
( last_date, previous_date )
VALUES ( '19122016', '08012017' ),
( '26122016', '01012017' );
select 'select *
into umkp.dbp.rosk_'+last_date+'_seg
from umkp.dbp.rosk_'+previous_date+'_seg'
FROM #dates;

How to copy exactly same schema of one table to another table using stored procedure

Initially, I'll be storing all columns of source table to single variable using stored procedure(SP1). This SP1 is called inside SP2 and that variable is inserted into destination table.
I know the approach but stuck in implementing it.
-- SP1
Create procedure insert_data
AS
Declare #data nvarchar(60)
Begin
EXEC get
--Here i have to insert
END
Go
--SP2
Create procedure get_column
AS
Declare
#e_id int , #e_name nvarchar(20) , #d_id int,#res nvarchar(50)
Begin
SET #e_id =(select Emp_ID from Dim_Employee where Emp_Name='Cathy');
SET #e_name =(select Emp_Name from Dim_Employee where emp_id=101);
SET #d_id =(select Dept_ID from Dim_Employee where emp_name='Cathy');
SET #res ='#e_id , #e_name , #d_id';
return #res
END
Go
if you already have destination table:
insert into DestTbl(emp_id, dept_id, ...)
select emp_id, dept_id, ...
from Dim_Employee d
where ...
if you dont and wish to create it
select emp_id, dept_id, ...
into DestTbl
from Dim_Employee d
where ...
if you still want to use variables
insert into DestTbl(emp_id, dept_id)
values (#emp_id, #dept_id, ...)
is this what you're asking for?
INSERT statement on msdn:
https://technet.microsoft.com/en-us/library/ms174335.aspx

Assigning Variable and Data-Retreival in two select statements with multiple rows

I understand you cannot combine assigning of variables and data-retrieval in the same select statement. I am using two select statements which will work well when a where clause is used and a single row is returned in the select that assigns the variables. How can I make these selects work together when multiple rows are returned from the select that assigns the variables?
DECLARE #CompanyName NVARCHAR(40)
DECLARE #ContactName NVARCHAR(30)
SELECT #CompanyName = CompanyName,
#ContactName = ContactName
FROM Customers
SELECT #CompanyName,#ContactName
Rather go for a table type variable like below
--Declare the table variable with the columns
declare #tab table (
CompanyName NVARCHAR(40),
ContactName NVARCHAR(30)
);
-- insert into table variable
insert into #tab(CompanyName, ContactName)
SELECT CompanyName, ContactName
FROM Customers
-- select from table variable
SELECT * from #tab;
To use a table variable, here's a really simple example based on yours:
declare #TableVar table (companyname varchar(40), contactname varchar(30))
insert into #TableVar
select companyname, contactname from Customers
Then you can select from your table variable, etc.

Resources