为什么这个查询不起作用

时间:2016-04-20 19:57:07

标签: sql sql-server openquery

我有以下SQL openquery

SELECT      @TSQL = 'SELECT * FROM OPENQUERY(RMSPROD2,''SELECT COUNT(DISTINCT W.Bond) AS NoBID_Count
                                                FROM TIB.WRMAST w
                                                WHERE (w.BID In (''No Bid'', ''No Cost'', ''None'') AND w.CtlNumber = ''''' + @WarControlID + ''''''')'

当我运行此查询时,我收到以下错误:

SELECT * FROM OPENQUERY(RMSPROD2,'SELECT COUNT(DISTINCT W.Bond) AS NoBond_Count
                                                FROM TIBURON.WRMAST w
                                                WHERE (w.Bond In ('No Bond', 'No Bail', 'None') AND w.CtlNumber = ''575403''')
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'No'.

什么是抛出的错误我在设计窗口中没有任何问题的迹象

3 个答案:

答案 0 :(得分:2)

问题的根本原因是您无意中关闭了此处的开头报价:

SELECT * FROM OPENQUERY(RMSPROD2,'SELECT COUNT(DISTINCT W.Bond) AS NoBond_Count
                                                FROM TIBURON.WRMAST w
                                                WHERE (w.Bond In ('

因此,你得到的错误接近否。例如,在java中,\是转义字符,因此为了确保连续性,我们必须写:

"SELECT COUNT(DISTINCT W.Bond) AS NoBond_Count
                                                    FROM TIBURON.WRMAST w
                                                    WHERE (w.Bond In (\'     "  //till the end

使用您选择的语言搜索适当的转义字符并应用它。

答案 1 :(得分:1)

我认为你错过了几个''字符,尝试下一个:

SELECT      @TSQL = 'SELECT * FROM OPENQUERY(RMSPROD2,''SELECT COUNT(DISTINCT   W.Bond) AS NoBID_Count
                                            FROM TIB.WRMAST w
                                            WHERE (w.BID In (''''No Bid'''', ''''No Cost'''', ''''None'''') AND w.CtlNumber = ''''' + @WarControlID + ''''''')'

答案 2 :(得分:0)

我找不到这个问题的答案所以我采用了不同的方法。我在这段代码中使用了OpenQuery

SELECT  @TSQL = 'SELECT * FROM OPENQUERY(RMSPROD2,''SELECT TIB.WRMAST.WR_INVL, TIB.WRMAST.WR_WARR_CTL,TIBURON.WRMAST.WR_BAIL,TIB.WRWCHG.WC_BAIL
                       FROM TIB.WRMAST 
                       LEFT JOIN TIBURON.WRWCHG
                       ON WRWCHG.WC_WR_CHAIN = WRMAST.WRMAST_ROW
                       WHERE TIBURON.WRMAST.WR_WARR_CTL = ''''' + @WarControlID + ''''''')'
Insert Into @WarrantBail
   EXEC (@TSQL)

并将结果放入临时表中。然后我就可以使用常规的T-SQL来编写剩下的所需语法。