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
Related
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...
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'
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.
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.
I'm using SqlServer for the first time, and in every single one of our create procedure scripts there is a block of code like below to remove the procedure if it already exists:
IF EXISTS (SELECT *
FROM information_schema.routines
WHERE routine_name = 'SomeProcedureName'
AND routine_type = 'PROCEDURE'
BEGIN
DROP PROCEDURE SomeProcedureName
END
//then the procedure definition
To stop cutting and pasting this boilerplate code in every file I would like to put this code in its own stored procedure so that instead the scripts would look like this:
DropIfRequired('SomeProcedureName')
//then the procedure definition
My attempt at a solution is:
CREATE PROCEDURE DropIfRequired
(
#procedureName varchar
)
AS
IF EXISTS (SELECT * FROM information_schema.routines
WHERE routine_name = #procedureName
AND routine_type = 'PROCEDURE')
BEGIN
DROP PROCEDURE #procedureName
END
But I then get the following error:
Msg 102, Level 15, State 1, Procedure DeleteProcedure, Line 10
Incorrect syntax near '#procedureName'.
Any ideas how to do what I want?
The full answer is:
DECLARE #SQL VARCHAR(8000)
SELECT #SQL = 'USE ' + DB_NAME() + CHAR(10)
SET #SQL = #SQL + 'DROP PROCEDURE ' + #procName
--PRINT #SQL
EXEC(#SQL)
The one given by Andrew will only work if the default database for your login is set to the database you want. When using dynamic sql you get a new database context. So if you do not have a default database set you will execute the command from master.
One thing to note is that in the DropIfRequired procedure, you have defined the procedure name as follows:
CREATE PROCEDURE DropIfRequired
(
#procedureName varchar
)
You need to define a length of the varchar parameter, otherwise SQL will assume a length of one character. Instead, do something like as follows (1000 should be more than enough for most procedure names)
CREATE PROCEDURE DropIfRequired
(
#procedureName varchar(1000)
)
its missing quotes, try adding them in with an exec statement.
EXEC( 'DROP PROCEDURE ''' + #procName + '''') ( all single quotes)