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.
Related
I want to be able to update the column of the same table in different databases at the same time within the same server, but to start before starting to fill it through a temporary table I wanted to test that it came out with a database, it should be clarified that the structure of the table it is the same in all the databases and that the script would be executed going through the temporary table row by row, so I needed to test it with at least one and then replaced the declared variables.
However, I get the following error, I have not found a solution or another way to do it, I do it to avoid doing it manually 1x1 on each database and it is done automatically:
Msg 4104, Level 16, State 1, Line 16
The multi-part identifier "test#gmail.com" could not be bound.
This is the code I tried:
use master
go
DECLARE #SQL NVARCHAR(MAX) = '';
DECLARE #NAMEBD NVARCHAR(MAX) = 'Here_goes_the_name_of_the_DB';
DECLARE #MAIL NVARCHAR(MAX) = 'test#gmail.com';
SELECT #SQL = #SQL +
'USE ' + QUOTENAME(NAME) + ';
UPDATE dbo.companyconfig
SET originMail ='+#MAIL+';'
FROM sys.databases
WHERE name = #NAMEBD;
EXEC sp_executesql #SQL;
I was hoping it would update but I only get the error shown.
I also tried using sp_MSforeachdb and it gives me the same result.
I already managed to solve it, I did it this way:
DECLARE #SQL NVARCHAR(MAX) = '';
DECLARE #NAMEBD NVARCHAR(MAX) = 'Here_goes_the_name_of_the_DB';
DECLARE #MAIL NVARCHAR(MAX) = 'test#gmail.com';
SELECT #SQL = #SQL + '
UPDATE compconfig
SET originMail ='''+#MAIL+'''
FROM '+QUOTENAME(#NAMEBD)+'.dbo.companyconfig As compconfig;'
FROM sys.databases
WHERE name = #NAMEBD;
EXEC sp_executesql #SQL;
It was necessary to set the field having to double the quotes.
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...
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
I am trying to create a simple stored procedure:
CREATE PROCEDURE SP_Test #FilePath int
AS
SELECT
LastName, FirstName
INTO
tmp_tblPerson
FROM
OPENROWSET('MSDASQL','Driver={Microsoft Access Text Driver (.txt, .csv)}','SELECT * FROM ' + #FilePath + "'")
GO
But I get a syntax error which I don't understand..?
Msg 102, Level 15, State 1, Procedure SP_Test, Line 12
Incorrect syntax near '+'.
Any ideas?
You can't use dynamic SQL when using using OPENROWSET. A workaround is to make the entire block use dynamically created SQL like this:
CREATE PROCEDURE SP_Test #FilePath int
AS
DECLARE #sql NVARCHAR(MAX) =
'SELECT LastName, FirstName
INTO tmp_tblPerson
FROM OPENROWSET(
''MSDASQL'',
''Driver={Microsoft Access Text Driver (.txt, .csv)}'',
''SELECT * FROM '' + #FilePath)'
EXEC(#sql)
As always with dynamic SQL, make sure you are not vulnerable to SQL injection attacks.
Additionally, your query appears to be incorrect as I doubt you have a table with an integer as a name.
#filepath is int, you probably want something like
'SELECT * FROM ' + convert(varchar,#FilePath)
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.