Error in Openquery Stored Procedure - sql

To keep this as simple as possible I have just copied the line of code causing an error. I'm trying to run a openquery in a stored procedure and keep getting the following error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '*'.
I'm pretty sure it is to do with where I have quotations but I really need a second pair of eyes as I have tried all sorts of combinations:
SET #SQL_ResultID = 'SELECT * FROM OPENQUERY([23-SQL3000], ''SELECT ResultID FROM [Portfolio].[dbo].[Program] P INNER JOIN [Portfolio].[dbo].[Results] A ON P.ProgramID = A.ProgramID WHERE ProgramName = ''''' + #P + ''''' AND ResultsName = ''''' + #A + ''''''')';
Thanks in advance

Related

sybase script don't understand trouble

I 'm not a regular of Sybase ASE.
Tring to make a script to add line into a tempory table.
sybase version 12.5.4
BEGIN
declare and init variable
--boucle
select * into #parTemp from Parution where 1=2
WHILE #dateCourante <= #dateFin
BEGIN
select #dpart1=datepart(mm,#dateCourante)
select #dpart2=datepart(dd,#dateCourante)
select #dpart3=datepart(dw,#dateCourante)
--si on est pas le 1er mai
if #dpart1 <> 5 AND #dpart2 <> 1
begin
--id parution
select #idPar = #idPar + 1
select #idParChaine = convert(varchar(10),#idPar)
--num parution
select #numPar = #numPar + 1
select #numParChaine = convert(varchar(20),#numPar)
--prix du jour courant
if datepart(dw,#dateCourante)=6
select #prixCourant = #prixVen
else
if datepart(dw,#dateCourante)=1
select #prixCourant = #prixDim
else
select #prixCourant = #prix
end
end
insert into #parTemp values (#idParChaine,#dateCourante,#numParChaine,#nbPagination,#prixCourant,#poids,#parCompt,#parOJD,#resVal)
end
select #dateCourante = dateadd(dd,1,#dateCourante)
END
END
Errors i get :
Error code 156, SQL state ZZZZZ: Incorrect syntax near the keyword 'WHILE'.
Error code 156, SQL state ZZZZZ: Incorrect syntax near the keyword 'end.
Error code 156, SQL state ZZZZZ: Incorrect syntax near the keyword 'End'.
i really don't understand, thank for help.
Pierre

Passing Cursor Result to send_dbmail as a Parameter

I've never worked with cursors before, and upon reading, this may not be the best approach, so by all means, makes suggestions.
I am attempting to pass the result set of a cursor to a query. Here's what I have so far:
DECLARE #PM varchar(50),
#c1 as CURSOR
SET #c1 = CURSOR FOR
SELECT PM
FROM PMtable
OPEN #c1;
FETCH NEXT FROM #c1 INTO #PM;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #emailBody nvarchar(max)
SET #emailBody = 'SELECT * FROM othertable WHERE PM = ' + #PM + ' ORDER BY PM';
EXEC msdb.dbo.sp_send_dbmail
#recipients = 'me#me.com',
#subject = 'test',
#query = #emailBody;
FETCH NEXT FROM #c1 INTO #PM;
END
CLOSE #c1;
DEALLOCATE #c1;
The idea is to send the #emailBody query result set as an email for every result in the cursor. For example, say the cursor returns three results: Bob, Jim, and Joe. I want to loop run the #emailBody query for each result from the cursor and send an email for each result.
When I run the query as is, I receive an error saying:
Msg 22050, Level 16, State 1, Line 0 Error formatting query, probably
invalid parameters
Msg 14661, Level 16, State 1, Procedure
sp_send_dbmail, Line 504 [Batch Start Line 0]
Query execution failed:
Msg 207, Level 16, State 1, Server SERVER, Line 9 Invalid column name
'Bob'.
Msg 207, Level 16, State 1, Server SERVER, Line 1 Invalid
column name 'Bob'.
I have no clue what's going on. Any ideas?
You need to add '':
SET #emailBody='SELECT * FROM othertable WHERE PM = ''' + #PM + ''' ORDER BY PM';
Be aware of possible SQL Injection.
How it works:
Msg 207, Level 16, State 1, Server SERVER, Line 9 Invalid column name 'Bob'.
SELECT * FROM othertable WHERE PM = Bob ORDER BY PM
vs.
SELECT * FROM othertable WHERE PM = 'Bob' ORDER BY PM
Please keep in mind that ORDER BY PM for one value does not change anything.

Open query - incorrect syntax next to passed in variable

I'm running this query
SET #Qry = ' SELECT [MLSTQT] INTO ##DISPENSED_LOCATION'
+' FROM OPENQUERY(MA,''SELECT MLSTQT FROM ES3.MD.MOC WHERE MLWHSL='''+ #ProcessOrder+''' '')'
EXEC (#Qry)
And I'm getting an error saying that there is incorrect syntax next to the value #ProcessOrder.
What's wrong with my query?
Seems it would be WHERE MLWHSL='10000' which is correct.

Getting various errors using dynamic SQL

SET #SQLSTATEMENT = 'INSERT INTO #MAX_STORAGE
SELECT MAX(A.[ROW])
FROM
(SELECT *
FROM [DATABASE].[dbo].[Refined_Est_Probability_09_MODIFIED]
WHERE
[FIPST_ENT] = ' + #FIPST_ENT + '
AND [FIPCNTY_ENT] = ' + #FIPCNTY_ENT + '
AND [SIC_ENT] = ' + #SIC2_ENT + '
AND [FMSZ_ENT] = ' + #FMSZENT_ENT + '
AND [ESTABLISHMENTS_AVAILABLE_FMSZEST <= ' + #MAXIMUM_FMSZEST+'] > 0) A'
EXEC(#SQLSTATEMENT)
I was running the dynamic SQL query above as part of a stored procedure I had written and got the following error:
Msg 207, Level 16, State 1, Line 7
Invalid column name 'A'.
I then changed my query so that it looked like this (eliminated the alias A):
SET #SQLSTATEMENT =
'INSERT INTO #MAX_STORAGE
SELECT
MAX([ROW])
FROM
(SELECT *
FROM [DATABASE].[dbo].[Refined_Est_Probability_09_MODIFIED]
WHERE [FIPST_ENT] = ' + #FIPST_ENT + '
AND [FIPCNTY_ENT] = ' + #FIPCNTY_ENT + '
AND [SIC_ENT] = ' + #SIC2_ENT + '
AND [FMSZ_ENT] = ' + #FMSZENT_ENT + '
AND [ESTABLISHMENTS_AVAILABLE_FMSZEST <= ' + #MAXIMUM_FMSZEST + '] > 0)'
EXEC(#SQLSTATEMENT)
But I still ran into an error (this time different):
Msg 102, level 15, state 1, line 9
Incorrect syntax near ')'
I declared the following variables earlier in the procedure with their respective data types/lengths seen next to them:
#FIPST_ENT CHAR(2)
#FIPCNTY_ENT CHAR(3)
#SIC2_ENT CHAR(2)
#FMSZENT_ENT CHAR(1)
#MAXIMUM_FMSZENT CHAR(1)
#SQLSTATEMENT VARCHAR(MAX)
Before this dynamic SQL statement was reached in the stored procedure, the temporary table #MAX_STORAGE was already created and contains only one column of datatype int.
Am I missing something I'm doing wrong? Any help would be greatly appreciated.
Thanks.
At bare minimum, you need to enclose string fields in escaped-single-quotes within the Dynamic SQL. The adaptation I show below is based on this comment on the Question:
FIPST_ENT is numeric in nature (i.e. 01-50) but cast as a character. Likewise with the other FIPCNTY_ENT and SIC2_ENT. FMSZENT is cast as a character but is sometimes numeric (i.e. 1-9) and other times non-numeric (i.e. A-C).
So it seems that only FMSZENT needs the escaped-single-quotes.
Also, using a derived query requires an alias. So whatever the initial problem was, you then introduced a new parse error by removing the alias ;-).
SET #SQLSTATEMENT =
'INSERT INTO #MAX_STORAGE
SELECT MAX(tmp.[ROW]) FROM
(SELECT * FROM [DATABASE].[dbo].[Refined_Est_Probability_09_MODIFIED]
WHERE [FIPST_ENT] = '+#FIPST_ENT+'
AND [FIPCNTY_ENT] = '+#FIPCNTY_ENT+'
AND [SIC_ENT] = '+#SIC2_ENT+'
AND [FMSZ_ENT] = '''+#FMSZENT_ENT+'''
AND [ESTABLISHMENTS_AVAILABLE_FMSZEST<='+#MAXIMUM_FMSZEST+'] > 0) tmp;'
Now, when it comes to debugging Dynamic SQL, the first step should be looking at what SQL you actually constructed, as it might not be what you think it should be:
PRINT #SQLSTATEMENT;

Dynamic UPDATE statement

I want to create a dynamic update query where I need to set a certain value in a column. But the column name needs to be SELECTed from another table.
I have already the following query:
UPDATE core.TableRes
SET (
SELECT Code FROM core.TableFields
INNER JOIN core.TableXTableFields ON TableXTableFields.FieldID = TableFields.FieldID
INNER JOIN core.TableResRefLinks ON TableResRefLinks.ExtraFieldID = TableXTableFields.ExtraFieldID
WHERE TableResRefLinks.TableResRefLinksID = RefLinks.TableResRefLinksID)
= (
SELECT Value FROM core.TableResRefLinks WHERE TableResRefLinksID = RefLinks.TableResRefLinksID)
FROM core.TableRes
INNER JOIN core.TableResRefLinks RefLinks ON RefLinks.ResourceID = TableRes.ResourceID
INNER JOIN core.TableXTableFields ON TableXTableFields.ExtraFieldID = RefLinks.ExtraFieldID
INNER JOIN core.TableFields ON TableFields.FieldID = TableXTableFields.FieldID
WHERE (EndDate IS NULL OR EndDate > GETDATE()) AND
(
SELECT Code FROM core.TableFields
INNER JOIN core.TableXTableFields ON TableXTableFields.FieldID = TableFields.FieldID
INNER JOIN core.TableResRefLinks ON TableResRefLinks.ExtraFieldID = TableXTableFields.ExtraFieldID
WHERE TableResRefLinks.TableResRefLinksID = RefLinks.TableResRefLinksID)
<>
(
SELECT Value FROM core.TableResRefLinks
WHERE TableResRefLinksID = RefLinks.TableResRefLinksID)
It gives me the following errors:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '('.
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '='.
Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'FROM'.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near '<'.
Is there a way to solve this? If I change the complete UPDATE and SET statements and replace them with a SELECT *, I get results.
EDIT
Here are the datatypes
TableFields.Code => nvarchar(100)
TableResRefLinks.Value => sql_variant
And the datatypes of the columns that have as column name TableFields.Code are set as sql_variant
You can't solve this using plain SQL. You would need some kind of scripting to build your statement. For example postgresql has a scripting language called "pgpsql" which allows building dynamic SQL statements. But this clearly depends on the underlying RDBMS.
By the way: this works with SELECT as you are doing simple sub-select.