SQLServer: Dynamic sql raise exception Could not find stored procedure - sql-server

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...

Related

Dynamic SQL server query with variables (Problems executing)

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'

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.

Receiving an error when executing a stored procedure that calls a linked server

I am in the process of setting up dynamic Reporting Services Shared Data Source using Linked Server. In doing so, I have created a stored procedure that requires a parameter and in testing the stored procedure (before setting everything else in SSRS) I am receiving an error. The stored Procedure code looks like this:
create procedure [dbo].[SelectFromServer3]
#ServerName sysname
as
begin
set nocount on;
declare #sql nvarchar(max)
set #sql = N'Select * from ' + quotename(#ServerName)+ '
.remotesvrnm.dbo.CUSTOMERS_DISAM_TABLE'
exec sp_executesql #sql
end
When I execute the following query to test the stored procedure:
EXEC SelectFromServer3 #ServerName = 'SQLSVRInstanceNM'
I receive the following error:
"Msg 208, Level 16, State 1, Line 1
Invalid object name 'remotesvrnm.dbo.CUSTOMERS_DISAM_TABLE'."
However, if I query the linked server directly with a query like:
EXEC ('SELECT * from remotesvrnm.dbo.CUSTOMERS_DISAM_TABLE') AT LNKDSRVRNM
The data is returned as expected. Even using an openquery statement works as expected:
Select * from openquery (LNKDSRVRNM, 'select * from remotesvrnmdbo.CUSTOMERS_DISAM_TABLE')
The guide that I am using to set this up I pulled from a Web search. I am at a loss as to how to resolve this. Any guidance would be greatly appreciated.
Thanks.
Can you use print #sql in your stored procedure to see what it evaluates to? Paste that into a new query window and see if you get the same error. If yes, please paste it here.
The code as shown works perfectly for me.
Thank you #PaulHoke for the suggestion to add to the stored procedure. I found that I had two things wrong... I found that I was missing a space in my stored procedure code. I was missing a space between the single quote and the .remotesvrnm.dbo.CUST....'.
The second issue was that when executing the stored procedure, I needed to use the name of the linked server, not the SQL Server Instance name. --The guide that I have been following, that I found on-line, was poorly written.

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.

Passing concat query parameters to SQL OPENQUERY

Due to the constraints within the workplace I have to use a local stored procedure to call another remote stored proc on a linked sql server, however the problem lies in passing a necessary parameter to the remote stored proc.
This is the query I constructed:
select *
from OPENQUERY([REMOTE_SRVR],'exec db.dbo.dwStoredProc_sp ''#id''')
In order to pass #id to the remote stored proc I understand I could concatenate the above as a string and then use exec
Something along the lines of:
set #query = 'select * from OPENQUERY([REMOTE_SRVR], ''EXEC db.dbo.dwStoredProc_sp '' #id '''''
exec(#query)
I cannot get the local stored proc to successfully call the other. The single quote mess doesn't help!
I get the error: Could not find stored procedure 's'
To help with the quote mess I like to do this in steps. It is more code but easier to understand. I am not sure from your example if #id is an integer. In that case you can lose the double quotes around __ID__.
set #query = 'EXEC db.dbo.dwStoredProc_sp ''__ID__'''
set #query = REPLACE(#query,'__ID__',#id)
set #query = REPLACE(#query,'''','''''')
set #query = REPLACE('SELECT * FROM OPENQUERY([REMOTE_SRVR], ''__REMOTEQUERY__'')','__REMOTEQUERY__',#query)
You could avoid dynamic queries by simply by using EXEC (..., ParamValue) AT LinkedServer (see product's documentation, example [L. Using a parameter with EXECUTE and AT linked_server_name]):
1) On target server:
CREATE PROCEDURE dbo.Proc1( #id NVARCHAR(50) )
AS
SELECT #id AS [id];
GO
2) On the source server you create the linked server and then you can call the stored procedure using EXEC ... AT ... syntax:
DECLARE #p1 NVARCHAR(50);
SET #p1 = N'DROP TABLE dbo.CocoJambo'
EXECUTE (N'dbo.Proc1 ? ' , #p1 ) AT LOCALINKEDSEREV
Output:
id
------------------------
DROP TABLE dbo.CocoJambo

Resources