0

我试图确定为什么我的存储过程不能正确运行。问题是当我使用连接参数时。完成后,我将拥有其中的 6 或 7 个,每个都建立在最后一个之上。我已经尝试了所有变体,包括 =、like、%、空格、没有空格,但无法提出正确的语法来使其可操作。我也做了一个“硬编码”测试,它工作正常,所以数据是正确的。帮助!谢谢

这是代码 -

ALTER PROCEDURE [dbo].[rspSCLTEST]

(@RRID as varchar(4),
@State as varchar(2),
@Sub as varchar(75))
AS
BEGIN

SET NOCOUNT ON;

DECLARE @SQL as varchar(4000)

SET @SQL = @State

--add the subdivision to the where statement
If @Sub = 'ALL'
SET @SQL = @SQL
ELSE
 SET @SQL += ' AND (C.SubDivision = '+ @Sub + ')'


SELECT C.CRID, C.DOT, C.RR, C.Pref, C.MP, C.Division, C.SubDivision, C.City, C.Street,
    C.State, C.County, C.RestrictedCounty, C.Remarks, C.SpecialInstructions, C.Route, C.ThirdAppRequired,
    C.MainTrks, C.OtherTrks, C.OnSpur, C.MaxSpeed, C.SubContracted, C.FenceEncroachment, C.Lat, C.Long,
    C.PropertyType, C.WarningDevice,C.Surface, C.ROWNE, C.ROWNW, C.ROWSE, C.ROWSW, C.ROWWidth, C.ExtNE,
    C.ExtNW, C.ExtSE, C.ExtSW, C.TempActive, C.PCO, A.App1Date, A.App1Cut, A.App1Spray, A.App1Inspect, 
    A.App2Date, A.App2Cut, A.App2Spray, A.App2Inspect, A.App3Date, A.App3Cut, A.App3Spray, A.App3Inspect

    FROM Crossings AS C LEFT OUTER JOIN AppData AS A ON C.CRID = A.CRID
    WHERE (C.DeletedCrossing = 0) AND (C.RR = @RRID)
    AND C.State = @SQL


END
4

2 回答 2

2

问题是您将动态 SQL 与参数替换混淆了。尝试这样的事情:

and c.state = @state and (@sub = 'ALL' or c.subdivision = @sub)

你写这个的方式,你正在检查:

and c.state = '<state> and c.subdivision = @sub'

也就是说,第二个从句没有被解释为一个从句,它被解释为状态的一部分。

于 2013-02-14T18:46:42.970 回答
0

这一行:

SET @SQL += ' AND (C.SubDivision = '+ @Sub + ')'

而这一行:

AND C.State = @SQL

出现嫌疑。我只能对您的数据做出假设,但看起来您有两个不同的对象:状态和细分。

C.State 中有哪些类型的数据?它只是州的缩写吗?(俄勒冈州、华盛顿州、密苏里州、明尼苏达州、亚利桑那州等)。如果是这样,您将永远不会得到肯定的结果WHERE C.State = WA123(假设“123”是一个细分值)。

无论如何,你能做这样的事情吗?-->

WHERE C.State = @state AND C.Subdivision = @sub
于 2013-02-14T18:56:25.960 回答