I’m attempting to determine why my stored procedure will not operate correctly.
The issue is when I utilize a concatenated parameter. When finished, I will have 6 or 7 of these, each built upon the last.
I’ve tried every variation including =, like, %, spaces, no spaces, and cannot come up with the correct syntax to make this operational.
I have also did a ‘hard coded’ test, and it works fine, so the data is correct.
HELP! Thanks
Here’s the code –
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
The problem is that you are confusing dynamic SQL with parameter replacement. Try something like this:
The way you had this written, you were checking for:
That is, the second clause is not being interpreted as a clause, it is being interpreted as part of the state.