list of dates to use in a script - sql-server

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;

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

Store result of SQL select in variables

I have a simple SELECT statement in SQL server that returns multiple values as follows :
1 Dog
2 Cat
3 Mouse
I need to know if there's a way to loop through them to store each value in a variable for example :
declare #animal1 nvarchar(50)
declare #animal2 nvarchar(50)
declare #animal3 nvarchar(50)
#animal1 = dog
#animal2 = cat
#animal3 = mouse
Eventually I want all the words to form a string and to insert that string in 1 column of a 2nd table
DECLARE #animals TABLE (
id int identity(1,1),--identity is optional if your select returns an id
name varchar(50)
);
insert into #animals
--Your Select statement here
Declare #string varchar(1000);
select #string = ISNULL(#string + ', ', '') + animals.animal_name
from
(
Select id, name from #animals
) animals (id, animal_name)
declare #my_string varchar(1000)
select #my_string = ISNULL(#my_string + ', ', '') + animals.animal_name
from
(
values
(1, 'dog'),
(2, 'cat'),
(3, 'mouse')
) animals (id, animal_name)
select #my_string
Not sure exactly what you mean, but can you use a table variable?
DECLARE #animals TABLE (
animal varchar(50)
);
and insert the values?

Creating table with dynamic columns using the PIVOT command

I have the following TSQL that I have been trying, without luck, to do 2 things with:
convert Nulls to 0
output to a temporary table I can use for
other operations.
Part of the result is captured in the attached:
What changes do I need to make to both capture the result into a temp table with dynamic columns, and eliminate the nulls?
Thanks.
DECLARE #cols NVARCHAR(MAX), #stmt NVARCHAR(MAX), #ParmDefinition NVARCHAR(MAX), #PVT3 NVARCHAR(MAX);
--Get distinct values of the PIVOT Column
SELECT #cols = ISNULL(#cols+', ', '')+'['+T.Cat+']'
FROM
(
SELECT TOP 100 CONVERT( VARCHAR(2), IncomeCategoryID) AS Cat
FROM Payroll.lu_IncomeCategory
WHERE IsAllowance <> 0
AND IncomeCategoryID IN
(
SELECT DISTINCT
IncomeCategoryID
FROM Payroll.Income
WHERE IncomeCategoryID <> 0
)
ORDER BY IncomeCategoryID
) AS T;
SELECT #stmt = N'
SELECT *
FROM (SELECT EmployeeID,IncomeCategoryID,
SUM(RateAmount) [Amount]
FROM Payroll.Income
GROUP BY EmployeeID, IncomeCategoryID ) as PayData
pivot
(
SUM([Amount])
FOR IncomeCategoryID IN ('+#cols+')
) as IncomePivot';
EXEC sp_executesql
#stmt = #stmt;
Done.
For the first challenge, it worked after using the #NullToZeroCols example in one of the previous posts on this forum. For my second challenge, I eventually Selected Into a Non-Temporary table which I can search for and drop each time I execute my TSQL command. I learnt the scope of the previously created temporary table could not allow me to use it after the PIVOT command was executed.

jdbc sql error: statement did not return a result set

I have two stored procedures as follows:
create stored procedure p1
as
select * from table1 where datediff(day, table1.[date], getdate())
create stored procedure p2
as
declare #t1 table(
ref varchar(20)
)
insert into #t1 select * from table1 where ref = 'some ref'
declare #t2 table(
fname varchar(20),
lname varchar(20),
email varchar(1000)
)
declare #len int = (select count(ref) from #t1)
while #len > 0
begin
declare #value varchar(20) = (select top 1 ref from #t1)
insert into #t2 select * from table2 where ref = #ref
delete from #t1
where ref = #value
set #len = (select count(ref) from #t1)
end
select * from #t2
Java code
....
String query = "Execute [p2]";
try(CallableStatement cstmt = conn.prepareCall(query);
ResultSet rs = cstmt.executeQuery()){
... some code
}
The table variable #t1 hold select result from a table 'table1'
The variable #len hold the number of rows in #t1
Using #len > 0 as condition in while loop, I want to select records from another table 'table2' the table variable #t2 hold the select records from 'table2'
The delete statement removes value from #t1
#len set to new number of rows in #t1
the last statement return all the records store in #t2
The first procedure works fine, but the second procedure works only in SQL Server.
I get this an error message in my java application
statement did not return a resultset
I want this to return a result set with the select statement I have at the
end of the query.
Please is there a way around this?
Your [p2] stored procedure needs to include SET NOCOUNT ON right at the beginning to suppress the "n rows affected" counts so JDBC doesn't get confused as to what it should put into the ResultSet:
CREATE PROCEDURE p2
AS
SET NOCOUNT ON;
declare #t1 table(
ref varchar(20)
)
-- ... and so on
For more information on SET NOCOUNT see
SET NOCOUNT (Transact-SQL)
For more information on precisely what gets returned from a stored procedure call, see
How to get everything back from a stored procedure using JDBC
use method "execute" instead of "executeQuery".

Pivot with a table variable

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

Resources