Script to create multiple stored procedures - sql

I am testing a scenario with a high number of stored procedures in mssql. Is there a way to script creating ~5000 stored procedures? My attempts have been futile.
declare #id int
select #id = 1
while #id >=1 and #id <= 1000
begin
CREATE PROCEDURE 'SelectAllCustomer'+ convert(varchar(5)) AS SELECT * FROM Customers
select #id = #id + 1
end
go
Fails with:
Msg 156, Level 15, State 1, Line 7 Incorrect syntax near the keyword
'PROCEDURE'.
Even just adding a parameter to the procedure name is failing:
CREATE PROCEDURE 'SelectAllCustomer'+ 'test' AS SELECT * FROM Customers
fails with:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near
'SelectAllCustomer'.

Here you go. Pretty straight forward.
declare #id int = 1
, #sql NVARCHAR(MAX)
while #id >=1 and #id <= 1000
begin
select #sql = 'CREATE PROCEDURE SelectAllCustomer'+ convert(varchar(5), #id) + ' AS SELECT * FROM Customers;'
exec sp_executesql #sql
select #id = #id + 1
end

Related

WHILE statement not recognizing declared variable

I am a novice SQL user and am attempting to perform a loop that displays the values of an object in 1 table referencing a value in a temp table that I created. Yes, I know there would be an extremely easy way to do this, however I am only looking to display the contents in this loop because I do not have write access to the database I am currently testing this on and eventually the loop will contain a few update statements. But I want to test the loop now and figure out how to reference the column in my temp table.
DECLARE #sql VARCHAR(MAX)
DECLARE #loop INT = 1
DECLARE #max INT
IF OBJECT_ID(N'tempdb..#temp') IS NOT NULL
BEGIN
DROP TABLE #temp
END
SELECT
0 AS 'row_counter', ID
INTO
#temp
FROM
Requests
WHERE
(Codes_IDs LIKE '%6581%' OR Codes_IDs LIKE '%6597%')
AND Codes_IDs LIKE '%6393%'
AND Type_ID = 6477
AND Codes_IDs NOT LIKE '%6484%'
DECLARE #counter int = 0
UPDATE #temp
SET #counter = row_counter = #counter + 1
--select * from #temp
SET #max = (SELECT MAX(row_counter) FROM #temp)
WHILE (#loop <= #max)
BEGIN
SET #sql = (N'Select * from requests where ID in (select ID from #temp where row_counter = #loop)')
EXEC(#sql)
SET #loop = #loop +1
END
DROP TABLE #temp;
I get these errors:
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "#loop".
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "#loop".
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "#loop".
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "#loop".
Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "#loop".
As you can see from my errors - for some reason it is not recognizing #loop even though I have declared it.

Trying to INSERT a SEQUENCE number into an INSERT statement but having issue [duplicate]

This question already has an answer here:
Error "Msg 245, Level 16, State 1, Line 22 Conversion failed when converting the varchar value 'July' to data type int."
(1 answer)
Closed 4 years ago.
I'm trying to create a sequence value that I need to increment in an INSERT statement using SQL Server 2014. I have a variable that contains the max number + 1 that I'm trying to INSERT into a temp table but that number needs to be incremented for each record being inserted into the TEMP TABLE. After googling this issue I found where I need to create a DYNAMIC SQL statement in order to use the variable value. However when I do that I get now a conversion error.
Any help/direction would be appreciated. Thank you.
Here is my code:
DECLARE #id int;
DECLARE #sql NVARCHAR(MAX);
SET #id = (SELECT MAX(rowNum)+1 FROM dbo.Focus_Export_Econ_DisadvantagedHHS_Staging_TEST)
SET #sql = 'CREATE SEQUENCE dbo.ID_Sequence
AS INT
START WITH ' + #id +
'INCREMENT BY 1
NO MAXVALUE'
EXEC #sql;
SELECT NEXT VALUE FOR #sql, T.*
INTO #TEMP_TEST --DROP TABLE #TEMP_TEST
FROM (SELECT h.SiteID, st.SchoolName, st.CEPSchool, st.StudentID, st.FName, st.LName, st.Grade, UPPER(LEFT(h.Status,1))+LOWER(SUBSTRING(h.Status,2,LEN(h.Status))) as Status,
(CASE
WHEN UPPER(h.Status) = 'FREE' THEN '01'
WHEN UPPER(h.Status) = 'REDUCED' THEN '02'
WHEN UPPER(h.Status) = 'PAID' THEN '00'
END) as EconomicDisadvantageCode,
(CASE
WHEN ltrim(h.AppType) = 'HS Survey' THEN 'HH'
END) as ApplicationTypeCode,
'HouseHold Survey' as ApplicationType,
st.ResAddr, st.City, st.ZipCode, st.State, st.Phone,
CONVERT(VARCHAR(10), CAST(h.Effective_Date as date), 101) as StatusEffectiveDate, h.End_Date, st.SchoolYear,
st.BirthDate, st.AppScanned, st.AppOnline, st.GracePeriodID,
(CASE
WHEN ISNUMERIC(h.APPID) = 1 THEN CONVERT(INT, h.APPID) ELSE NULL
END) as ApplicationID
FROM #TEMP_HHS_Historical_Records h
INNER JOIN dbo.Focus_Export_Econ_DisadvantagedHHS_Staging_TEST st
ON h.CustomerID = st.StudentID) as T;
The error I'm getting is:
Msg 245, Level 16, State 1, Line 384
Conversion failed when converting the varchar value 'CREATE SEQUENCE dbo.ID_Sequence
AS INT
START WITH ' to data type int.
I think the problem is in the dynamic SQL. You can fix this by doing:
SET #sql = 'CREATE SEQUENCE dbo.ID_Sequence
AS INT
START WITH ' + cast(#id as varchar(255) + '
INCREMENT BY 1
NO MAXVALUE'
EXEC (#sql);
I am not sure if the create sequence statement allows parameters, but that would be a better choice than munging the string with the value like this.
you need to cast the ID to nvarchar, like this:
DECLARE #id int;
DECLARE #sql NVARCHAR(MAX);
SET #id = (SELECT MAX(rowNum)+1 FROM dbo.Focus_Export_Econ_DisadvantagedHHS_Staging_TEST)
SET #sql = 'CREATE SEQUENCE dbo.ID_Sequence
AS INT
START WITH ' + cast(#id as nvarchar(100)) +
'INCREMENT BY 1
NO MAXVALUE'
exec sp_executesql #sql;
--TO GET THE VALUE INTO #ID
SELECT #id = NEXT VALUE FOR dbo.ID_Sequence
You just need to create the sequence one time.
The you can iterate and get the #id value.
Hope it helps!

Dynamic Table Name and Paramers in SQL Stored Procedure

create procedure dbo.move_pos
(
#id int,
#tbl varchar(50)
)
as
begin
declare #pos int
exec('select '+#pos+'=POS from '+#tbl+' where id='+#id)
exec('update '+#tbl+' set POS=POS+1 where POS<'+#pos)
end
In above procedure column POS is of type int. But when I m executing this procedure it is showing following error :
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '='.
I m using SQL SERVER 2012. Need help. Thanks in advance !!!
I would recommend rethinking all this dynamic sql stored procedures.
However, if you really must use dynamic sql, try this instead:
create procedure dbo.move_pos
(
#id int,
#tbl varchar(50)
)
as
begin
declare #sql nvarchar(max);
set #sql = 'update ' + QUOTENAME(#tbl) + '
set POS = POS + 1
where POS < (
select POS
from ' + QUOTENAME(#tbl) + '
where id = '+ cast(#id as nvarchar(10)
)'
exec(#sql)
end

How to drop multi temporary table?

How to drop multiple temporary table from SQL Server
Below code give this error :
msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'drop'.
declare #deptno int = 1
while #deptno > (Select COUNT(*) from tbl_deptseat)+1
Begin
Declare #deptnamevar nvarchar(20) = '##dept'+ cast(#deptno as nvarchar(10))
exec (drop table (#deptnamevar))
End
declare #deptno int = 1
while #deptno < (Select COUNT(*) from tbl_deptseat)+1
Begin
Declare #deptnamevar nvarchar(20) = '##dept'+ cast(#deptno as nvarchar(10))
Declare #dropquery nvarchar(20) = 'drop table '+ #deptnamevar
exec (#dropquery)
set #deptno = #deptno + 1
End
This seems like a very strange way of approaching data processing. I wouldn't recommend putting such logic in table names. Instead, the logic belongs in columns.
But, you want to use dynamic SQL:
declare #deptno int = 1;
declare #sql nvarchar(max);
while #deptno < (Select COUNT(*) from tbl_deptseat)+1
Begin
Declare #deptnamevar nvarchar(20) = '##dept'+ cast(#deptno as nvarchar(10));
set #sql = 'drop table ' + #deptnamevar;
exec(#sql) ;
set #deptno = #deptno + 1;
End;

Getting an error when passing the table name as parameter to a function

I am new to SQL query and here I am trying to get the complete name from dbo.Customer_List table and have written this code. However when try to run am getting the following error. I don't know what I am doing wrong.
Error message is:
Msg 1087, Level 16, State 1, Procedure getFullName, Line 11
Must declare the table variable "#tblName".
Msg 1087, Level 16, State 1, Procedure getFullName, Line 14
Must declare the table variable "#tblName".
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'Last_Name'.
Code is:
IF OBJECT_ID (N'dbo.getFullName', N'FN') IS NOT NULL
DROP FUNCTION getFullName
GO
Create function dbo.getFullName(#tblName varchar(30),#fstName varchar(50), #lstName varchar(50) ) returns varchar(101)
As
Begin
Declare #rowCount int
Declare #rowIteration int
Declare #temp varchar(101)
Select #rowCount = count(*) from #tblName
Set #rowIteration = 1
While ( #rowIteration <= #rowCount)
Select #temp = #fstName+' '+#lstName from #tblName where #tblName.Customer_Id = #rowIteration
Begin
Set #rowIteration = #rowIteration + 1
End
return #temp
End
Go
Declare #tblName varchar(30),#fstName varchar(50), #lstName varchar(50)
set #tblName = convert(varchar(30),'dbo.Customer_List')
set #fstName = convert(varchar(50),'dbo.Customer_List.First_Name')
set #lstName = convert(varchar(50),'dbo.Customer_List.Last_Name')
Execute ('select dbo.getFullName('+ #tblName+','+ #fstName+','+ #lstName )
You are essentially trying to perform dynamic sql here without performing it properly. You can't just pass in a variable as a table name, that's why you're getting your error.
You need to recreate this as a stored procedure (or at least you will in sql-server which does not like DML transactions in functions) and use the following dynamic sql:
Declare #sql nvarchar(100)
Set #sql = 'Set #int = (Select count(*) from ' + #tblName + ')'
execute sp_executesql #sql, N'#int int output', #int = #rowCount output