Creating SQL tables dynamically in a loop - sql

I need to dynamically create X tables. The X is calculated on the fly based on a series of other calculations that get passed in. I've written the following dynamic code in an effort to create a loop and generate a create statement each time.
I can't use global tables for this project.
DECLARE #cnt_v varchar(10)
DECLARE #SQL NVARCHAR(max) = ''
DECLARE #season_counter int = 5
SET #cnt = 1
SET #cnt_v = CONVERT(varchar(10), #cnt)
WHILE #cnt <= #season_counter
BEGIN
select #SQL = #SQL + 'create table #Season_year' + #cnt_v + ' (customer_no int, order_no int, order_dt datetime, season_no int)'
exec sp_executesql #SQL
set #sql = ''
select #SQL = #SQL + 'select * from #Season_year' + #cnt_v
exec sp_executesql #SQL
select #cnt = #cnt + 1
select #cnt_v = CONVERT(varchar(10), #cnt)
select #sql = ''
END
The output of the above code is the following errors
When manually create the tables, by typing
create table #Season_year1 (customer_no int, order_no int, order_dt datetime, season_no int)'
then use my dynamic loop to insert data, update records and ultimately drop the temp tables everything works without an issue. The problem is solely creating the tables dynamically.
If this approach isn't going to work, how else could I do this?
Thank you

Each one of your dynamic sql statements is run within its own scope, so in the SELECT * FROM #Season_year5 has no idea what #Season_year5 is. In the first dynamic SQL statement it's created and destroyed all with the execution of sp_executesql. If you combine them both into a single dynamic SQL statement then you will be able to access the temp table in other statements.
DECLARE #cnt INT = 1;
DECLARE #cnt_v varchar(10)
DECLARE #SQL NVARCHAR(max) = ''
DECLARE #season_counter int = 5
SET #cnt = 1
SET #cnt_v = CONVERT(varchar(10), #cnt)
WHILE #cnt <= #season_counter
BEGIN
select #SQL = #SQL + N'create table #Season_year' + #cnt_v + N' (customer_no int, order_no int, order_dt datetime, season_no int);
select * from #Season_year' + #cnt_v + N';'
exec sp_executesql #SQL
select #cnt = #cnt + 1
select #cnt_v = CONVERT(varchar(10), #cnt)
select #sql = ''
END

Related

How to declare temponary/variable table with a dynamic number of column

I have table like this:
Table Name|Number of columns
How to dynamically create temporary tables inside stored procedure with names from first table, and variable columns named e.g. col1, col2, etc..
I also need to insert values to them and make another logic on them.
Example:
Table1|3
Table1(col1 nvarchar(max), col2 nvarchar(max), col3 nvarchar(max))
You will need to use dynamic sql like below:
declare #counter int = 1
declare #numberOfCols int = 3 -- OR you can use ->(select numberofcolumns from firsttable)
declare #dynamic nvarchar(max) = ''
declare #sql nvarchar(max) = 'CREATE TABLE #TEMP (';
while #counter <= #numberofCols
begin
set #dynamic = #dynamic + 'col'+cast(#counter as nvarchar(5))+' nvarchar(max) ';
if(#counter <> #numberOfCols)
begin
set #dynamic = #dynamic + ', ';
end
set #counter = #counter + 1
end
set #sql = #sql + #dynamic + ') select * from #temp'
select #sql
EXECUTE sp_executesql #sql
I have created a stored procedure regarding your question. I wish it can help you.
ALTER PROCEDURE P_ProcedureName
#NumberOfColumns INT=2 --expected 1 or more column
AS
DECLARE #SQLString VARCHAR(MAX)=''
DECLARE #Seq INT=2
IF #NumberOfColumns=0
BEGIN
SELECT 'Please add valid number of column'
RETURN
END
CREATE TABLE #Table
(
Id INT NOT NULL IDENTITY(1,1)
,Column1 VARCHAR(MAX)
)
WHILE #Seq<=#NumberOfColumns
BEGIN
SET #SQLString=#SQLString+'ALTER TABLE #Table ADD Column'+CAST(#Seq AS VARCHAR)+' VARCHAR(MAX)'+char(13)
PRINT(#SQLString)
SET #Seq +=1
END
EXEC(#SQLString)
SELECT * FROM #Table
GO
P_ProcedureName 5

T sql - How to store results from a dynamic query using EXEC or EXECUTE sp_executesql

I am trying to write a dynamic query. Let's say i have a table like below, which represents the hierarchy level of a sales agent:
AgentNumber Level1Agent Level2Agent Level3Agent Level4Agent Level5Agent
1122334455 1122334499 1122334488 1122334477 1122334466 1122334455
I want to be able to dynamically select a level based on a specified agent. My EXECUTE statement seems to work correctly, but how do I get the result stored in a variable I can use later? Every answer I have found seems to only get me a success return variable, not the actual query result.
Below is my code:
DECLARE #level INT = 1;
DECLARE #agent CHAR(10) = 1122334455;
DECLARE #colname NVARCHAR(11) = CONCAT('Level',#level,'Agent');
DECLARE #whereclause NVARCHAR(35) = CONCAT('WHERE AgentNumber = ',#agent);
DECLARE #qry NVARCHAR(300) = 'SELECT ' + #colname + ' FROM dbo.TABLE ' + #whereclause;
DECLARE #up NVARCHAR(10);
EXECUTE sp_executesql #qry, #up OUT
SELECT #up
The output of #up is NULL. If I change the last two lines to:
EXECUTE #up = sp_executesql #qry
SELECT #up
Now the output of #up is 0.
I want the output of 1122334499 and I need it stored in a variable that can later be used and inserted into a table.
Here is a fully functional example of how you can do this. Notice this is using a parameterized where clause and quotename around the column name in the dynamic sql to prevent sql injection.
if OBJECT_ID('tempdb..#Agents') is not null
drop table #Agents
create table #Agents
(
AgentNumber char(10)
, Level1Agent char(10)
, Level2Agent char(10)
, Level3Agent char(10)
, Level4Agent char(10)
, Level5Agent char(10)
)
insert #Agents
select '1122334455', '1122334499', '1122334488', '1122334477', '1122334466', '1122334455'
DECLARE #level INT = 3;
DECLARE #agent CHAR(10) = 1122334455;
DECLARE #colname NVARCHAR(11) = CONCAT('Level',#level,'Agent');
declare #agentout char(10)
DECLARE #qry NVARCHAR(300) = 'SELECT #agent_out = ' + quotename(#colname) + ' FROM #Agents WHERE AgentNumber = #agentin';
EXECUTE sp_executesql #qry, N'#agentin char(10), #agent_out char(10) output', #agentin = #agent, #agent_out = #agentout output
select #agentout
You can try this :
DECLARE #level INT = 1;
DECLARE #agent CHAR(10) = 1122334455;
DECLARE #colname NVARCHAR(11) = CONCAT('Level',#level,'Agent');
DECLARE #whereclause NVARCHAR(35) = CONCAT('WHERE AgentNumber = ',#agent);
DECLARE #qry NVARCHAR(300) = 'SELECT #agentout=' + #colname + ' FROM dbo.TABLE ' + #whereclause;
DECLARE #up NVARCHAR(10);
EXECUTE sp_executesql #qry, N'#agentout NVARCHAR(10) OUTPUT', #agentout=#up OUTPUT
SELECT #up
Create a variable table and makes your query insert the results you want there. Something like this:
declare #results table(field1 varchar(max), field2 varchar(max));
declare #sqlStatement varchar(max);
set #sqlStatement = 'insert into #results(field1, field2) select field1, field2 from table';
EXECUTE #sqlStatement;
select * from #results; --It will print the results from your sql statement!

Sum up values from databases and parametrize it. [SQL Server]

I want to sum up values from several databases. At this moment I have three databases: SPA_PROD, SPB_PROD and SPC_PROD.
My SQL query:
IF EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[TESTSUM]')
AND TYPE IN (N'P',N'PC'))
DROP PROCEDURE [dbo].[TESTSUM]
GO
CREATE PROC TESTSUM
AS
BEGIN
DECLARE #dbName SYSNAME,
#ObjectSUM INT,
#d datetime
SET #d = '20141113'
DECLARE #SQL NVARCHAR(MAX)
DECLARE #DBObjectStats TABLE (
--DBName SYSNAME,
DBObjects INT)
DECLARE curAllDBs CURSOR FOR
SELECT name
FROM MASTER.dbo.sysdatabases
WHERE name like '%PROD'
ORDER BY name
OPEN curAllDBs
FETCH curAllDBs INTO #dbName
WHILE (##FETCH_STATUS = 0) -- db loop
BEGIN
--SQL QUERY
SET #SQL = 'select #dbObjects = sum(doctotal) from ' +
QuoteName(#dbName) + '..Invoice
where DocDate = ''' + cast(#d as varchar(25)) + ''''
PRINT #SQL -- Debugging
EXEC sp_executesql #SQL, N'#dbObjects int output',
#dbObjects = #ObjectSUM output
INSERT #DBObjectStats
SELECT #ObjecSUM
FETCH curAllDBs INTO #dbName
END
CLOSE curAllDBs
DEALLOCATE curAllDBs
-- Return results
SELECT sum(DBObjects) [InvoiceSUM] FROM #DBObjectStats
END
GO
-- Execute stored procedure
EXEC TESTSUM
GO
And this work perfect and giving me right sum from all my DBs: 120 000$ ( 25 000 from SPA_PROD , 95 000 SPC_PROD and 0 (NULL) from SPB_PROD.
What I want to do:
I would like to parametrize, which allows me to choose date and databases. For example I want to choose SPA_PROD and SPB_PROD with date 2014-01-01 in another case I want all databases (SPA + SPB + SPC with another date.
Is this even possible? Any ideas?
I can use everything what gives me SQL Server 2012 and T-SQL. Maybe this technology offers me easiest way to do this.
I am also using SAP Crystal Reports to convert SQL output into a beautiful report.
Sorry for my English and I tried to describe to you my problem as far as I could. If you want any additional information which helps u to help me -> ask me :).
You can create a User-Defined Table Type:
CREATE TYPE DBTable AS TABLE
(
DBName VARCHAR(128)
);
You can use it as an input parameter of your stored procedure. As well as the date parameter.
CREATE PROCEDURE TESTSUM
#Databases DBTable READONLY
,#Date DATETIME
AS
BEGIN
...
...
...
You call it like this:
DECLARE #T AS DBTable;
DECLARE #D AS DATETIME = GETDATE();
INSERT INTO #T VALUES ('DB1', 'DB2', 'DB3')
EXEC TESTSUM #T, #D
maybe instead of
SELECT name
FROM MASTER.dbo.sysdatabases
use
SELECT name
FROM #temptable
and insert into #temptable specific db you want
Using your example I modified it to accept a string of database names (generated through you crystal reports select action). Then passing this string with the date in question to first validate the database exist and if online add the required union clause to the generated SQL code.
CREATE PROCEDURE TESTSUM
#DbNameS NVARCHAR(max)
,#Date DATETIME
AS
BEGIN
DECLARE #SQL NVARCHAR(MAX) = ''
/* ADD EXTRA ',' RO STRING ARRAY OF DATABASES */
SET #DbNameS = #DbNameS + ',';
DECLARE #L INT = LEN(#DbNameS);
DECLARE #D INT = 0;
DECLARE #LD INT = 1;
DECLARE #DBF VARCHAR(50);
DECLARE #ACTIVE INT = 0;
/* START SQL QUERY */
SET #SQL = 'SELECT SUM([InvoiceSUM]) AS [InvoiceSUM] FROM ( SELECT '''' AS DB, 0.00 AS [InvoiceSUM]' + CHAR(13)
/* LOOP THROUGH EACH DBF NAME PASSED CHECKING IF VALID AND ONLINE */
WHILE #D < #L
BEGIN
SET #D = CHARINDEX(',', #DbNameS,#LD);
IF #LD != #D
BEGIN
SET #DBF = SUBSTRING(#DbNameS,#LD,#D-#LD)
/* VALIDATE DBF IS VALID AND ACTIVE */
SELECT #ACTIVE = COUNT(*) FROM SYS.databases WHERE name = #DBF AND [state] = 0
IF #ACTIVE = 1
BEGIN
/*
BEGIN CODE TO UNION THE SUM RESULTS FOR EACH ACTIVE AND VALID DBF
TO MAKE IT WORK WITH SOME EXISTING DBF's ON MY SYSTEM I CHANGED THE SUMMARY CODE FOR TESTING
*/
SET #SQL = #SQL + 'UNION SELECT '''+ #DBF +''' AS DB, ISNULL(SUM( CAST(DVE AS DECIMAL(18,10)) ),0) AS [InvoiceSUM] FROM '+ #DBF + '.DBO.SO_MSTR WHERE CAST(RecordCreated AS DATE) = '''+ CAST(#Date AS VARCHAR(20)) + '''' + CHAR(13)
END;
END;
SET #LD = #D + 1;
END;
/* CLOSE OUT UNION SUMMARY QUERY */
SET #SQL = #SQL + ') AS DATA'
/* OUTPUT RESULTS */
EXEC SP_EXECUTESQL #SQL
END;
Crystal reports would effective be generating this code: EXEC TESTSUM 'SPA_PROD,SPB_PROD,SPC_PROD','12/09/2014'

Can I use variable in condition statement as value with where condition that test that value

I have the following stored procedure:
ALTER proc [dbo].[insertperoll] #name nvarchar(50) , #snum int , #gnum int
as
DECLARE #value nvarchar(10)
SET #value = 's'+CONVERT(nvarchar(50),#snum)
DECLARE #sqlText nvarchar(1000);
DECLARE #sqlText2 nvarchar(1000);
DECLARE #sqlText3 nvarchar(1000);
declare #g nvarchar(50) = '''g1'''
SET #sqlText = N'SELECT ' + #value + N' FROM dbo.GrideBtable'
SET #sqlText2 = ' where Gnumber = '+#g --here is the problem it error invalid column name -- the #g is value from the table condition
set #sqlText3 = #sqlText+#sqlText2
Exec (#sqlText3) -- here how can i save the result of the exec into varibale
declare #sal nvarchar(50) = #sqlText3
insert employ (name,Snumber,Gnumber,Salary) values(#name,#snum,#gnum,#sal)
QUESTION: How to put in condition variable gets value from the table when i exec it it think that the #g is column but its not its a value from the table to test it so i display one value after the exec the other QUESTION is how to save the result from the exec in variable and then use that value
I'm using SQL Server 2008 (9.0 RTM)
This will be a stored procedure
Thanks in advance
Not sure why you would go through all the loops to insert into the table where you can have a simple insert query like ..
ALTER PROC dbo.[insertperoll] #name nvarchar(50) , #snum int , #gnum int
AS
insert employ (name, Snumber, Gnumber, Salary)
select #name
, #sum
, #gnum
, case when #snum = 1 then s1
when #snum = 2 then s2
when #snum = 3 then s3
when #snum = 4 then s4
end as Salary
from dbo.GrideBtable
where Gnumber = #gnum
If your intent is to have the proc retrieve a salary value from a column determined from the parameter snum and then make an insert into employ using the values passed as parameters and the salary retrieved I think you could refactor your procedure to this:
CREATE proc [dbo].[insertperoll] #name nvarchar(50) , #snum int , #gnum int AS
DECLARE #g NVARCHAR(50) = 'g1'
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'INSERT employ (name,Snumber,Gnumber,Salary) '
SET #sql += N'SELECT ' + QUOTENAME(#name, '''')
SET #sql += N', ' + CAST(#snum AS NVARCHAR(50))
SET #sql += N', ' + CAST(#gnum AS NVARCHAR(50))
SET #sql += N', s' + CAST(#snum AS NVARCHAR(50))
SET #sql += N' FROM dbo.GrideBtable'
SET #sql += N' WHERE Gnumber = ' + QUOTENAME(#g, '''')
EXEC (#sql)
Of course you could add the #g variable to the procedure parameters instead of having it hard coded in the procedure and call it as:
EXEC insertperoll #name='john', #snum=10, #gnum=100, #g='g1'
Sample SQL Fiddle (with some assumptions made about table structure)
You could do this using sp_executesql instead of exec() since this will allow you to use parameters, you can use an output parameter to get the value from the query:
DECLARE #SQL NVARCHAR(MAX) = N'SELECT #val = ' + CONVERT(NVARCHAR(10),#snum) +
N' FROM dbo.GrideBtable WHERE Gnumber = #G1';
DECLARE #val INT; -- NOT SURE OF DATATYPE REQUIRED
EXECUTE sp_executesql #SQL, N'#G1 VARCHAR(20), #val INT OUT', 'G1', #val OUT;

Select from table with dynamic compute name

I want to write query in which name table will dynamicaly compute. I have code like this below. What should I put in 'magic code' region?
DECLARE #myTableName nvarchar(100) = 'sch'
+ CAST(#nowYear as VARCHAR(5))
+ 'Q'
+ CAST(#nowQuarter as VARCHAR(3))
+ '.[tVisits]'
-- magic code --
myTable = DoSomething(#aktTableName)
-- magic code --
SELECT * FROM myTable
I use MS SQL Server 2012
You need use the dynamic SQL -
DECLARE
#nowYear INT = 2013
, #nowQuarter INT = 1
DECLARE #myTableName NVARCHAR(100) = '[sch'
+ CAST(#nowYear AS VARCHAR(5))
+ 'Q'
+ CAST(#nowQuarter AS VARCHAR(3))
+ '].[tVisits]'
DECLARE #SQL NVARCHAR(MAX) = N'SELECT * FROM ' + #myTableName
EXEC sys.sp_executesql #SQL
Instead of SELECT * FROM myTable
You need to do something like
DECLARE #sql nvarchar(4000)
SELECT #sql = ' SELECT * FROM ' + #myTable -- #myTable is a string containing qualified table name
EXEC sp_executesql #sql
Note that sp_executesql allows for a parameterized query - check its documentation