I am trying to Execute a stored procedure that requires to variables be passing into to it. One is a static, the other is a dynamic variable.
DECLARE #Filt DATETIME
SET #Filt = (SELECT DISTINCT MAX(Date) FROM Data.db.Staging)
SELECT * INTO #tempData FROM OPENROWSET('SQLNCLI', 'Server=ISR14 \MSSQL2012;Trusted_Connection=yes;', 'EXEC GetData.db.Staging #Mode = ''Date'' #Filt ')
but that doesn't work, got the error back
"Msg 8180, Level 16, State 1, Line 1
Statement(s) could not be prepared.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '#Filt'."
I'm guessing it is because Filt is dynamic statement. So I tried this
DECLARE #FilterData DATETIME
DECLARE #sql VARCHAR(200)
SET #Filt = (SELECT DISTINCT MAX(AsOfDate) FROM Data.db.Staging)
SET #sql = 'EXEC GetData.db.Staging #Mode = ''Date'' #Filt = ' + #Filt
SELECT * INTO #tempData FROM OPENROWSET('SQLNCLI', 'Server=ISR14\MSSQL2012;Trusted_Connection=yes;',
#sql)
But I get the message back
"Msg 102, Level 15, State 1, Line 24
Incorrect syntax near '#sql'."
It seems that OPENROWSET can only accept strings. But I want to pass a variable that is dynamic.
You have to put the whole statement into a variable and run it, and convert #FilterData to a varchar to concatenate it.
You can't use variables with openquery/openrowset.
Try this and check the print output... if it works and looks ok, then EXEC(#sql2)
DECLARE #FilterData DATETIME
DECLARE #sql VARCHAR(200), #sql2 VARCHAR(500)
SET #FilterData = '2014-07-01'--(SELECT DISTINCT MAX(AsOfDate) FROM Data.db.Staging)
SET #sql = 'EXEC GetData.db.Staging #Mode = ''''Date'''', #Filt = ''''' + CONVERT(VARCHAR(20),#FilterData ,120) + ''''''
SET #sql2 = 'SELECT * INTO #tempData FROM OPENROWSET(''SQLNCLI'', ''Server=ISR14\MSSQL2012;Trusted_Connection=yes;'',
'''+#sql+''')'
print #sql2
--exec(#sql2)
You need to make the whole query dynamic, not sure if I got it nailed down, but something like:
DECLARE #Filt DATETIME
,#sql VARCHAR(MAX)
SET #Filt = (SELECT MAX(Date) FROM Data.db.Staging)
SET #sql = 'SELECT * INTO #tempData FROM OPENROWSET(''SQLNCLI'', ''Server=ISR14 \MSSQL2012;Trusted_Connection=yes;'', ''EXEC GetData.db.Staging #Mode = ''''Date''' +#Filt+ ')'
EXEC (#sql)
Related
I am trying to use dynamic SQL to populate a statement and run it:
DECLARE #ENTY_ID INT;
DECLARE #FIELD_ID INT;
DECLARE #VALUE NVARCHAR(50);
DECLARE #ENTY_TABLE_NAME NVARCHAR(500);
DECLARE #SQL NVARCHAR(MAX);
SET #ENTY_ID = 1;
SET #FIELD_ID = 90;
SET #VALUE = '0';
SET #ENTY_TABLE_NAME =
(SELECT TOP 1 ENTY_TABLE_NAME
FROM ENTY
WHERE ENTY.ENTY_ID=#ENTY_ID);
SET #SQL = '
SELECT DISTINCT ATTR_VAL
FROM #ENTY_TABLE_NAME
WHERE FIELD_ID = #FIELD_ID AND ATTR_VAL LIKE %#VALUE%
ORDER BY ATTR_VAL';
SET #SQL = replace(#SQL, '#ENTY_TABLE_NAME', #ENTY_TABLE_NAME + '_ATTR');
SET #SQL = replace(#SQL, '#FIELD_ID', #FIELD_ID);
SET #SQL = replace(#SQL, '#VALUE', #VALUE);
EXEC SP_EXECUTESQL #SQL;
When I run all of the lines EXCEPT the last EXEC, the command completes successfully.
When I run it all together I get:
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near '0'.
I don't see how a syntax issue is being called. How can I get this to run the query in the #SQL variable?
You are missing the single quotes in LIKE %#VALUE%, it should be LIKE ' %#VALUE%':
SET #SQL = '
SELECT DISTINCT ATTR_VAL
FROM #ENTY_TABLE_NAME
WHERE FIELD_ID = #FIELD_ID AND ATTR_VAL LIKE ''%#VALUE%''
ORDER BY ATTR_VAL';
Why does this fail with the following error message:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'reporting_rawdata_v2'.
the name of the table is "dbo.reporting_rawdata_v2" but either with/without "dbo" it still fails...
Use reporting2
Go
Declare #Backupdate varchar(25), #sql NVARCHAR(max)
Set #Backupdate = REPLACE(REPLACE(CAST(CONVERT(VARCHAR(20), SYSDATETIME(), 100) as varchar),' ','_'),':', '')
Select #Backupdate
SET #sql = 'Select * Into reporting_rawdata_BACKUP_' + #Backupdate + 'From reporting_rawdata_v2';
EXEC (#sql);
No space between dynamically named table and From
SET #sql = 'Select * Into reporting_rawdata_BACKUP_' + #Backupdate + ' From reporting_rawdata_v2';
EXEC (#sql);
Simple question but wasting time to looking for the answer. I have stored procedure like this
ALTER PROCEDURE [dbo].[sinau]
#id varchar (max)
AS
BEGIN
SET NOCOUNT ON;
declare
#select varchar (4000),
#from varchar (4000),
#where varchar (4000),
#final varchar (4000)
-- Insert statements for procedure here
set #select = 'select *'
set #from = 'from permohonan'
set #where= 'where idpermohonan= '+#id
set #final=#select+#from+#where
execute (#final)
END
After I input parameter and exec that SP, the result is
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '='.
Could you fix this ? Thanks
You need to add spaces:
set #select = 'select * '
set #from = 'from permohonan '
set #where= 'where idpermohonan= '+#id
because without it you get:
select *from permohonanwhere idpermohonan= ...
You should always check your query:
IF #debug = 1
PRINT #select+#from+#where;
But for completness you should not concatenate string and use parametrized sp_executesql:
ALTER PROCEDURE [dbo].[sinau]
#id varchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #query NVARCHAR(MAX);
SET #query =
N'SELECT *
FROM permohonan
WHERE idpermohonan = #id;';
EXEC [dbo].[sp_executesql]
#query,
N'#id VARCHAR(MAX)',
#id;
END
Using Dynamic SQL can be tricky so I strongly recommend to read The Curse and Blessings of Dynamic SQL
I understand that you cannot include variables in OPENQUERY so the work around is dynamic SQL and I did the following:
DECLARE #etd AS DATETIME = '2014-06-28'
DECLARE #source AS VARCHAR(46)
DECLARE #dbName AS VARCHAR(30)
DECLARE #query AS VARCHAR(MAX)
DECLARE #openQuery AS VARCHAR(MAX)
SELECT TOP(1) #source = [Source], #dbName = DbName
FROM dbo.SomeTable
WHERE SystemCode = 'SomeSystem'
SET #query = 'SELECT *
FROM [' + #dbName + '].dbo.Table1 t1
LEFT JOIN [' + #dbName + '].dbo.Table2 t2 ON t1.bookno = t2.tranno
WHERE (YEAR(t1.etddate) = ' + CAST(YEAR(#etd) AS VARCHAR(4)) +
' AND MONTH(t1.etddate) = ' + CAST(MONTH(#etd) AS VARCHAR(2)) +
' AND DAY(t1.etddate) = ' + CAST(DAY(#etd) AS VARCHAR(2)) +')'
SET #openQuery = 'SELECT * FROM OPENQUERY([' + #source + '],''' + #query + ''')'
EXECUTE (#openQuery)
When I use SELECT #openQuery I don't see anything wrong with the query string, but once I execute it, I received the following error:
OLE DB provider "SQLNCLI11" for linked server "xxx.xxx.xxx.xxx,1433" returned message "Deferred prepare could not be completed.".
Msg 8180, Level 16, State 1, Line 1
Statement(s) could not be prepared.
Msg 208, Level 16, State 1, Line 1
Invalid object name 'xxxx.dbo.t1'. (where 'xxxx' is the table name variable)
I've been searching for answers but I cannot find any, I really need your help guys.
You might temporarily change the EXECUTE to PRINT (PRINT #openQuery), see what SQL is actually being generated, then attempt to run the generated sql directly in SSMS. It might be obvious when you see the generated sql, but if not, you might get a more descriptive error message.
I spend lot of time to figure out, what is the error,
l have code like this.
DECLARE #GeofenceName nvarchar(50) = '';
DECLARE #sql AS NVARCHAR(MAX)
SET #sql = N'select * from GeofenceMaster where GeofenceName = GName'
EXEC sp_executesql #sql,N'GName nvarchar(50)',#GeofenceName
PRINT #sql
it throw a error like this.
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'GName'.
select * from GeofenceMaster where GeofenceName = GName
anybody know which cause this problem?
UPDATE:
The original answer is incorrect. No parentheses should be required. See http://msdn.microsoft.com/en-us/library/ms188001(v=sql.105).aspx
New answer
Try
DECLARE #GeofenceName nvarchar(50) = '';
DECLARE #sql AS NVARCHAR(MAX)
set #sql = N'select * from GeofenceMaster where GeofenceName = #GName'
EXEC sp_executesql #sql,N'GName nvarchar(50)',#GName=#GeofenceName
I've amended the SQL itself, ... = GName becomes ... = #GName and the execution, ..., #GeofenceName becomes ..., #GName = #GeofenceName.
Original answer
You need to add some brackets.
Instead of
EXEC sp_executesql #sql,N'GName nvarchar(50)',#GeofenceName
Try
EXEC sp_executesql(#sql,N'GName nvarchar(50)',#GeofenceName)
the problem is in the variable "GName" (should have #, in this case would #GName), try with the following code, this works perfectly (for more info, see this LINK):
DECLARE #sql AS NVARCHAR(MAX)
declare #GName AS nvarchar(50) = ''
SET #sql = N'select * from GeofenceMaster where GeofenceName = ''' + #GName + ''''
EXEC sp_executesql #sql,N'#GName nvarchar(50)',GName
PRINT #sql