Dynamic Table Name and Paramers in SQL Stored Procedure - sql

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

Related

SQL Server stored procedure with while condition containing table variable

I have a table where the name of the country changes regularly, like my_table_US_NA, my_table_CAN_NA, my_table_MEX_NA and so on:
create table my_table_US_NA(id int)
insert into my_table_US_NA(id) values (1)
insert into my_table_US_NA(id) values (2)
insert into my_table_US_NA(id) values (3)
insert into my_table_US_NA(id) values (4)
select * from my_table_US_NA
id
----
1
2
3
4
I have a stored procedure like this:
create procedure my_looping_procedure (#Country varchar(10))
as
begin
declare #MyTable varchar(50), #COUNTER int
set #COUNTER = 1
set #MyTable = concat('my_table_', #Country, '_NA')
while (#COUNTER <= (select max(id) from #MyTable))
begin
set #COUNTER = #COUNTER + 1
print #COUNTER
end
end
When I try to compile the procedure, I get this error:
Msg 1087, Level 16, State 1, Procedure my_looping_procedure, Line 15 [Batch Start Line 0]
Must declare the table variable "#MyTable"
I tried moving the while loop into its own little variable:
create procedure my_looping_procedure (#Country varchar(10))
as
begin
declare #MyTable varchar(50),
#sql_loop varchar(max),
#COUNTER int
set #COUNTER = 1
set #MyTable = concat('my_table_', #Country, '_NA')
-- inner variable here
select #sql_loop = '
while (' + #COUNTER + '<= (select max(id) from ' + #MyTable + '))
begin
set ' + #COUNTER + ' = ' + #COUNTER + ' + 1
print ' + #COUNTER + '
end'
exec(#sql_loop)
end
That compiles but returns an error when I try to execute it exec my_looping_procedure:
Msg 245, Level 16, State 1, Procedure my_looping_procedure, Line 16 [Batch Start Line 26]
Conversion failed when converting the varchar value 'WHILE (' to data type int.
I tried declaring and setting all the variables inside #sql_loop:
alter procedure my_looping_procedure (#Country varchar(10))
as
begin
declare #sql_loop varchar(max)
select #sql_loop = '
declare
#MyTable varchar(50),
#COUNTER INT
SET #COUNTER = 1
set #MyTable = concat(''my_table_'', ' + #Country + ', ''_NA'')
WHILE (#COUNTER <= (select max(id) from ' + #MyTable + '))
BEGIN
SET #COUNTER = #COUNTER + 1
print #COUNTER
end'
exec(#sql_loop)
end
This compiles but still errors on execution:
Msg 1087, Level 16, State 1, Line 38
Must declare the table variable "#MyTable".
I then declared the #MyTable variable in the beginning again:
alter procedure my_looping_procedure (#Country varchar(10))
as
begin
declare
#MyTable varchar(50),
#sql_loop varchar(max)
set #MyTable = concat('my_table_', #Country, '_NA')
select #sql_loop = '
declare
#MyTable varchar(50),
#COUNTER INT,
#Country varchar(10),
SET #COUNTER = 1
set #MyTable = concat(''my_table_'', ' + #Country + ', ''_NA'')
WHILE (#COUNTER <= (select max(id) from ' + #MyTable + ' ))
BEGIN
SET #COUNTER = #COUNTER + 1
print #COUNTER
end'
exec(#sql_loop)
end
This actually compiles but complains about the country:
Msg 207, Level 16, State 1, Line 37
Invalid column name 'US'.
Finally, I commented out the initial table set statement:
alter procedure my_looping_procedure (#Country varchar(10))
as
begin
declare
#MyTable varchar(50),
#sql_loop varchar(max)
-- set #MyTable = concat('my_table_', #Country, '_NA')
select #sql_loop = '
declare
#MyTable varchar(50),
#COUNTER INT,
#Country varchar(10),
#MaxCount int
SET #COUNTER = 1
set #MyTable = concat(''my_table_'', ' + #Country + ', ''_NA'')
WHILE (#COUNTER <= (select max(id) from ' + #MyTable + ' ))
BEGIN
SET #COUNTER = #COUNTER + 1
print #COUNTER
end'
exec(#sql_loop)
end
This compiles AND runs, but does nothing.
Can anybody figure out what I'm doing wrong?
Some background:
This is an example of the problem with the parameter and the while loop, not the actual code. As for why it's done this way, the initial design was just for one hard-coded country. When more countries were added, the scripts were copied with new countries hard-coded.
The initial designer is no longer with the company. My current task is just to make a generic piece of code that can be used no matter how many more countries we add. There are hundreds of scripts like this and very little time and few resources on the project.
I genuinely appreciate the suggestions of using a temp table, but the tables are used in other processes. Until we iron out the underlying issues with the process, we are stuck with this design.
Without questioning why you are doing it this way (but those comments are very useful and should be carefully considered). Here is your working code:
create table #my_table_US_NA(id int);
insert into #my_table_US_NA(id) values (1),(2),(3),(4);
declare #MyTable varchar(50), #Country varchar(10);
set #Country = 'US';
set #MyTable = quotename(concat('#my_table_', #Country, '_NA'));
declare #Sql nvarchar(max) = 'declare #COUNTER INT = 1; WHILE (#COUNTER <= (select max(id) from [' + #MyTable + ']))
BEGIN
SET #COUNTER = #COUNTER + 1
print #COUNTER
end';
exec(#Sql);
drop table #my_table_US_NA;
Note 1: I've added quotename as per Larnu's suggestion to avoid the possibility of injection.
Note 2: Your table design doesn't align with how relational databases are intended to be used. You wouldn't normally have a separate table for each country, you would normally have a country column which allows you to segment the table by country. No good design should end up relying on dynamic SQL, sure you might need it for some edge cases but not your main business flow.
I think that you want to gather the data from the country-specific table and then loop through the country-specific data. I would take the approach of using a "temp" table so that you can insert data from a dynamic SQL statement. Here's what I mean:
create procedure my_looping_procedure as
begin
create table #MyTable (id int)
declare #COUNTER int, #Country varchar(3), #MyTable varchar(50), #sql varchar(100)
SET #COUNTER = 1
set #Country = 'US'
set #MyTable = concat('my_table_', #Country, '_NA')
set #sql = 'insert #MyTable (id) select * from ' + #MyTable
exec(#sql)
WHILE (#COUNTER<= (select max(id) from #MyTable))
BEGIN
SET #COUNTER = #COUNTER + 1
print #COUNTER
end
end
go
exec my_looping_procedure
I eventually resolved the issue by declaring the expression inside the while loop as a text string, like so: set #WhileExpr = concat('#COUNTER <= (select max(id) from ', #MyTable) then using it inside the while parenthesis WHILE (' + #WhileExpr + '))
I apologize for wasting your time.

SQL Server 2017 - Database mail stored procedure

I have a stored procedure which basically I want to do the following:
Create temp table (if not exists) and populate with data
Output the query to SSMS, and assigning the query a variable (#sql)
Using the query, e-mail the contents of the query to the recipients
My script is this:
Create Procedure ListDaysofYear(#year as integer)
as
Declare #sql as varchar(200), #DBqry as varchar(200),
#tab as char(1) = char(9)
Declare #dayofyear as bigint = 1
Declare #monthofyear as int = 1
Declare #day as int = 1
Declare #curDate as datetime
Declare #DB as varchar(40)
Declare #sql2 as varchar(40)
Set #curDate = datefromparts(#year, #monthofyear, #day)
Set #DB = 'msdb'
IF OBJECT_ID('tempdb.dbo.##daysofYear','U') IS NOT NULL
DROP TABLE ##daysofYear
--Print 'YES'
ELSE
CREATE TABLE ##daysofYear
(
cDate DATETIME PRIMARY KEY NOT NULL,
cMonth VARCHAR(20) NOT NULL,
cDay VARCHAR(20) NOT NULL
)
WHILE year(#curDate) = #year
BEGIN
-- Insert rows based on each day of the year
INSERT INTO ##daysofYear (cDate, cMonth, cDay)
VALUES( (#curDate),
(DATENAME([MONTH], #curDate)),
(DATENAME([WEEKDAY], #curDate)) )
SET #curDate = #curDate + 1
END
--Output file to SSMS query window
Select dy.* from ##daysofYear dy;
Set #sql = 'Select dy.* from ##daysofYear dy;'
Set #sql2 = 'Use ' + #DB + '; Exec msdb.dbo.sp_send_dbmail
#profile_name = ''Notifications'',
#recipients = ''mikemirabelli6#hotmail.com'',
#attach_query_result_as_file = 1,
#query_attachment_filename = ''daysofyear.txt'',
#query_result_separator = '',
#body = ''The attached output file - DaysofYear table'',
#query = ''Select dy.* from ##daysofYear dy'' ;'
--Execute sp_sqlexec #sql
Exec(#sql2)
Basically when I run the execute line:
Exec dbo.ListDaysofYear 2018 ;
I get the following message the first time:
Msg 208, Level 16, State 0, Procedure dbo.ListDaysofYear, Line 25
[Batch Start Line 52] Invalid object name '##daysofYear
I believe it’s related to the "DROP TABLE" part of the T-SQL.
Thanks
Think i found the issue:
IF OBJECT_ID('tempdb.dbo.##daysofYear','U') IS NOT NULL <-- here you are dropping the table if exisit but doesn't create it so it throws an error in line 25 where it tries to insert data (to a table you dropped). i suggest replacing drop table with TRUNCATE TABLE.

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

Error coming while creating UDF in Sql Server 2005

Does anyone know what's wrong with this code block.
CREATE FUNCTION [dbo].[udfGetPoint]
(
#UserID INT,
#SqlCountry VARCHAR(1000)
)
RETURNS INT
AS
BEGIN
DECLARE #Points INT
SET #Points = 1
DECLARE #RecordCount sysname
IF #SqlCountry <> ''
BEGIN
EXEC sp_executesql
N'SELECT #DynamicCount = COUNT(UserID) FROM Country WHERE UserID = '+#UserID+' AND LCValues IN (' + #SqlCountry + ')'
,N'#DynamicCount sysname OUTPUT'
,#RecordCount OUTPUT
IF #RecordCount > 0
SET #Points = #Points + 1
END
RETURN #Points
END
If i execute this i got following error:
Msg 102, Level 15, State 1, Procedure udfGetPoint, Line 15
Incorrect syntax near '+'.
You can't concatenate in the parameter setting of a stored procedure.
DECLARE #sql varchar(2000)
SET #SQL = 'SELECT #DynamicCount = COUNT(UserID) FROM Country WHERE UserID = '+#UserID+' AND LCValues IN (' + #SqlCountry + ')'
EXEC sp_executesql
#SQL
,N'#DynamicCount sysname OUTPUT'
,#RecordCount OUTPUT