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

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

Related

Script to create multiple stored procedures

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

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.

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;

Incorrect syntax near '.'

I am trying to run a stored procedure in SQL Server 2008. After I created the procedure, I selected the option to "Script Table AS EXECUTE", which (after entering the SELECT queries for the field names) comes up as:
DECLARE #RC int
DECLARE #tablename varchar(50)
DECLARE #field1 varchar(25)
DECLARE #field2 varchar(25)
SELECT #tablename = '[databasename].[dbo].[tablename]'
SELECT #field1 = 'name'
SELECT #field2 = 'amount'
EXECUTE #RC = [databasename].[dbo].[procedurename]
#tablename
,#field1
,#field2
GO
I then get the following error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'
but there doesn't appear to be any '.' anywhere near line 1 or anywhere other than the table names?
Nothing is wrong with that code. As it stated in the comment that something is wrong with your stored procedure. Take the source code of the procedure, delete lines with create/alter and the input parameters until the first begin. After that remove the last END. Replace all the parameters in the code and execute it as normal TSQL statement. In that case you'll easily find where it is failing.
Just to be sure that your code is working, execute following script:
CREATE PROCEDURE [procedurename]
#tablename VARCHAR(1000)
,#field1 VARCHAR(1000)
,#field2 VARCHAR(1000)
AS
BEGIN
SELECT 1
END
GO
DECLARE #RC int
DECLARE #tablename varchar(50)
DECLARE #field1 varchar(25)
DECLARE #field2 varchar(25)
SELECT #tablename = '[databasename].[dbo].[tablename]'
SELECT #field1 = 'name'
SELECT #field2 = 'amount'
EXECUTE #RC = [dbo].[procedurename]
#tablename
,#field1
,#field2
GO
DROP PROCEDURE [procedurename]
GO