我正在尝试确定为什么我的存储过程无法正常运行。 问题是当我使用连接参数时。完成后,我将有6或7个,每个都建立在最后一个。 我已经尝试了每个变体,包括=,像,%,空格,没有空格,并且无法提供正确的语法来使其可操作。 我还做了一个'硬编码'测试,它工作正常,所以数据是正确的。 救命!感谢
这是代码 -
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
答案 0 :(得分:2)
问题是您将动态SQL与参数替换混淆。尝试这样的事情:
and c.state = @state and (@sub = 'ALL' or c.subdivision = @sub)
你写这篇文章的方式,你正在检查:
and c.state = '<state> and c.subdivision = @sub'
也就是说,第二个子句不被解释为子句,它被解释为状态的一部分。
答案 1 :(得分:0)
这一行:
SET @SQL += ' AND (C.SubDivision = '+ @Sub + ')'
这一行:
AND C.State = @SQL
显得怀疑。我只能对你的数据做出假设,但看起来你有两个不同的对象:State和Sub-division。
C.State中有哪些数据?它只是国家缩写吗? (OR,WA,MO,MN,AZ等)。如果是这样,你永远不会得到WHERE C.State = WA123
的正面结果(假设'123'是细分值)。
无论如何,你能做这样的事吗? - &GT;
WHERE C.State = @state AND C.Subdivision = @sub