Ref: I looked at SQL Server stored procedure parameters to get a start.
Issue:
I want to make different SQL statements depending on the data passed in via the stored procedure. This example deals with one version but there will be several variations and I want to keep my code consise.
Error:
Msg 102, Level 15, State 1, Procedure spSearchGrid, Line 60 Incorrect syntax near '@SQL'. Msg 103, Level 15, State 4, Procedure spSearchGrid, Line 60 The identifier that starts with 'SELECT p.ID AS ID, p.UPRN AS UPRN, COALESCE(a.OverallRiskCategory,'Unknown') AS OverallRiskCategory, COALESCE(a.TypeOfUtility,'U' is too long. Maximum length is 128. Msg 102, Level 15, State 1, Procedure spSearchGrid, Line 65 Incorrect syntax near '@SQL'. Msg 103, Level 15, State 4, Procedure spSearchGrid, Line 66 The identifier that starts with 'a.SurveyDate between @sDateFrom and @sDateTo AND (p.UPRN LIKE '%' + @sUPRN + '%' or p.PostCode LIKE '%' + @sPostcode + ' is too long. Maximum length is 128. Msg 102, Level 15, State 1, Procedure spSearchGrid, Line 76 Incorrect syntax near 'END'.
Tried:
I have tried using both single and double speechmarks around the outside but this has not helped fixed the issue.
Code:
USE [Database]
GO
/****** Object: StoredProcedure [dbo].[spSearchGrid] Script Date: 18/06/2015 15:14:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
ALTER PROCEDURE [dbo].[spSearchGrid]
@sUPRN varchar(150),
@sPostcode varchar(20),
@sDateFrom datetime,
@sDateTo datetime,
--@sUCARN varchar(20),
@sPropertyName varchar(20),
@sStreet varchar(150),
@sSurveyCompany varchar(150),
@sRiskRating varchar(150),
@sRegion varchar(150)
-- Add the parameters for the stored procedure here
--@test1 VARCHAR(30) OUTPUT
AS
BEGIN
--and
DECLARE @SQL VARCHAR(MAX)
If @sUPRN = 'Test'
BEGIN
@SQL = SELECT p.ID AS ID, p.UPRN AS UPRN, COALESCE(a.OverallRiskCategory,'Unknown') AS OverallRiskCategory, COALESCE(a.TypeOfUtility,'Unknown') AS TypeOfUtility, COALESCE(a.SurveyDate,'') AS SurveyDate, COALESCE(a.ItemRef, '') AS ItemRef, COALESCE(a.NextAsbestosSurveyDue,'') AS NextAsbestosSurveyDue , COALESCE(a.Recommendations,'NO DATA') AS Recommendations, COALESCE(a.StatusOfIssue,'0') As StatusOfIssue
FROM TblProperty AS p LEFT JOIN TblAsbestos AS a on a.UPRN = p.UPRN WHERE
IF LTRIM(RTRIM(@sRiskRating)) = '1234xyz'
@SQL += a.OverallRiskCategory = LTRIM(RTRIM(@sRiskRating)) AND
@SQL += a.SurveyDate between @sDateFrom and @sDateTo AND (p.UPRN LIKE '%' + @sUPRN + '%' or
p.PostCode LIKE '%' + @sPostcode + '%' or
p.ShopName LIKE '%' + @sPropertyName + '%' or
p.Street LIKE '%' + @sStreet + '%' or
p.Reg = @sRegion or
a.SurveyCompany LIKE '%' + @sSurveyCompany + '%' )
END
--PRINT(@SQL)
EXEC(@SQL)
END