Dynamic SQL server query with variables (Problems executing) - sql-server

This is a far smaller version of a query that basically needs a variable of the table on which everything is run.
When I run the procedure I get the error message:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'table'.
alter procedure james_tester
#tablename nvarchar(200)
as
BEGIN
declare #sql nvarchar(max)
set #sql =
'
select * from '
+ #tablename
EXECUTE sp_executesql #sql
END
To fix this i tried using things like quotename and played around with the format but nothing seems to have worked yet.
execute james_tester 'dbo.Calendar table' (That is the table I am wanting to query)

The problem lies in how you call your procedure.
execute james_tester 'dbo.Calendar table'
should be
execute james_tester 'dbo.Calendar'
Hence the error message :
Incorrect syntax near the keyword 'table'.

Table is a keyword of sql server.
So you couldn't use it as an alias with out [].
Try this
execute james_tester 'dbo.Calendar [table]'
or
execute james_tester 'dbo.Calendar t'
or
execute james_tester 'dbo.Calendar'

Related

SQLServer: Dynamic sql raise exception Could not find stored procedure

This is my dynamic sql.
DECLARE #SQL varchar(MAX)
DECLARE #Data varchar(MAX)
SET #Data='ALFKI'' OR ContactName=''Ana Trujillo'''
SET #SQL='select * from Customers Where CustomerID='''+#Data+''
print #SQL
exec (#SQL)
when i print then i get this sql select * from Customers Where CustomerID='ALFKI' this sql is right one but when i replace print #SQL with exec #SQL and execute the dynamic sql again then i am getting error called
Msg 2812, Level 16, State 62, Line 8 Could not find stored procedure
'select * from Customers Where CustomerID='ALFKI''.
not clear where i made the mistake. please give me some hint where is the problem in above dynamic sql. thanks
There is EXEC to execute a stored procedure. Of course there is no SP with the name select * from Customers....
And there is EXEC(), a function!, which is used to execute dynamically created statements.
Just use EXEC(#SQL) instead.
Another way with some more options is sp_executesql with wide support for parameters. You can use this to pass the ALFKI as parameter. Otherwise you might be open for SQL injection...

SQL variable for Database Name

I am trying to pass a database name in as a parameter and execute some dynamic SQL. As a test I created this:
declare #HRMSDatabase_1 nvarchar(50) = N'FirstDatabase',
#Example_1 nvarchar(max) =
'select #HRMSDatabase'
execute sp_executesql #Example_1, N'#HRMSDatabase nvarchar(50)', #HRMSDatabase_1
which returns FirstDatabase as I expected.
When I try this:
declare #HRMSDatabase_2 nvarchar(50) = N'FirstDatabase',
#Example_2 nvarchar(max) =
'select
''Test''
from
#HRMSDatabase.dbo.hrpersnl hp'
execute sp_executesql #Example_2, N'#HRMSDatabase nvarchar(50)', #HRMSDatabase_2
I get an error message:
Msg 102, Level 15, State 1, Line 29
Incorrect syntax near '.'.
Is what I am trying to do possible? I cannot simply use a USE FirstDatabase as I have a few databases I have to query in the same dynamic SQL using inner joins.
Also, I cannot use SQLCMD as this script gets executed from a GUI.
Basically, I don't believe you can parameterize the database name in the table specifier. Instead try this,
DECLARE #HRMSDatabase NVARCHAR(50) = N'FirstDatabase';
DECLARE #Example3 NVARCHAR(MAX) ='SELECT
''Test''
FROM
' + QUOTENAME(#HRMSDatabase) + '.[dbo].[hrpersnl] hp';
EXEC sp_executesql #Example3;
As you'll note, it's important that the #HRMSDatabase is not recieved from user input as this would be susceptible to injection attacks.

Copy stored procedure from one database to another using T-sql

I'm using sql server
I want to copy a stored procedure from one database to another using T-sql,
but my stored procedure contains dynamic sql.
I get the definition from sys.sql_modules and execute it using this code
exec sp_executesql #sp_definition
but it gives me error:
Msg 102, Level 15, State 1, Line 23 Incorrect syntax near ' + #tblName + '
Example of my stored procedure
CREATE Procedure insertRow
(
#tblName nvarchar(250),
#value nvarchar(250)
)
AS
DECLARE #script nvarchar(1000)
SET #script='INSERT INTO '+#tblName +' VALUES('+#value+')'
exec #script
How can i escape the quotes to execute it succesfully
The solution is to escape quotes properly and using ''' instead of only one quote

T-SQL variable show Incorrect syntax near '#tableName'

It shows an error ,when try to run this
declare #tableName VARCHAR(250)
select #tableName='['+SCHEMA_NAME(schema_id)+'].['+name+']'
FROM sys.tables
WHERE '['+SCHEMA_NAME(schema_id)+'].['+name+']'='[Management].[Table_1]'
print #tableName
TRUNCATE table #tableName
Incorrect syntax near '#tableName'.
That is correct. You cannot use variables to pass table names.
You can use dynamic SQL:
declare #sql nvarchar(max);
set #sql = replace('TRUNCATE table #tableName', '#tableName', #tableName);
exec sp_executesql #sql;
SQL statements are allowed to have parameters for constants, but not for identifiers. This is not only a SQL Server limitation, but a limitation in all (?) databases. Dynamic sql is often used for this purpose.
TSQL sp_executesql

SQL Server Stored Procedure Parameter

I am trying to create a stored procedure with one parameter. I want the stored procedure to perform an update query and the parameter that I pass when it executes is the table that should be updated. I have been unsuccessful with creating the procedure with the parameter.
CREATE PROCEDURE cleanq7 #tablename varchar(100)
AS
BEGIN
UPDATE #tablename
SET IMPOSSIBLE_CASE = '1'
WHERE q7='1'
GO
The message I receive when I run this is:
Msg 102, Level 15, State 1, Procedure cleanq7, Line 6
Incorrect syntax near '1'.
I tried just the indented update query on a table in test database and it functioned as expected, so I imagine this is an issue with my syntax for declaring the stored procedure.
Any help would be greatly appreciated!
CREATE PROCEDURE cleanq7
#tablename NVARCHAR(128)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Sql NVARCHAR(MAX);
SET #Sql = N'UPDATE ' + QUOTENAME(#tablename) +
N' SET IMPOSSIBLE_CASE = ''1''
WHERE q7 = ''1'''
EXECUTE sp_executesql #Sql
END
GO
Since you are passing the table name you will need to build your UPDATE statement dynamically and then Execute it using system stored procedure sp_executesql.
When you pass the table name as a String Sql Server treats it as a string not as an Object name. Using QUOTENAME() function puts square brackets [] around the passed table name and then sql server treats it as an object name.
QuoteName function also protects you against Sql injection attack.

Resources