T-SQL - How to write a conditional join

后端 未结 9 1872
轻奢々
轻奢々 2021-01-30 13:07

I have a stored procedure with a number of parameters. I would like to write my query so that it joins with certain tables but only if a particular parameter has a value. Take

9条回答
  •  离开以前
    2021-01-30 13:24

    You should be able to expand on this...

    DECLARE @SQL varchar(max)
    
        SET @SQL = 'SELECT * FROM PERSON P'
    
        IF NULLIF(@ADDRESSID,"") IS NULL SET @SQL = @SQL + " INNER JOIN ADDRESSES A ON P.AddressID = A.AddressID"
    
        EXEC sp_executesql @SQL, N'@ADDRESSID int', @ADDRESSID
    

提交回复
热议问题