我有一个SQL查询,我需要有条件地在WHERE子句中添加一个'AND'子句 我有一个变量(@Payment)只需要包含在WHERE子句中,如果它是非null。 我不应该使用IF条件。
这是我的代码..
SELECT Fname,lname,city, addressline1, state,zip
FROM table1
JOIN addresstable on table1.id = addresstable.addid
WHERE state = @state
AND ((@Payment IS NULL) OR (payment LIKE + '%' + @Payment + '%' ) OR (payment LIKE + '%all%' ) )
在示例中,如果@Payment IS NULL,那么我不希望将最后一个'AND'子句添加到where子句。
答案 0 :(得分:1)
试试这个:
select fname,lname,city, addressline1, state,zip
from table1
join addresstable on table1.id = addresstable.addid
where state = @state
and (
(@Payment is null)
or
(payment like @PaymentLike)
)
当您调用此查询时。你需要传递2个参数。
假设您将'payment'变量传递给@Payment
您将通过:(付款== null)? “%all%”:(“%”+付款+“%”)到@PaymentLike
确保这项工作。
答案 1 :(得分:0)
您不提供任何测试数据或架构,因此很难确定,但这可能就是您所需要的。
我不确定此条件的目的OR (payment LIKE + '%all%' )
它会将结果限制为包含“all”一词的所有行。
我假设(虽然你没有在你的问题中说明)你试图从addresstable和table1中的任何匹配行返回所有行。使用left join。如果不是这种情况,您可以将此AND ((payment LIKE + '%' + COALESCE(@Payment,'') + '%' ) OR (payment LIKE + '%all%' ) )
移回WHERE子句并将LEFT JOIN更改为INNER JOIN。
--Test data
DECLARE @table1 AS TABLE(addid INT, payment VARCHAR(20))
DECLARE @addresstable AS TABLE(addid INT, Fname VARCHAR(20),lname VARCHAR(20),city VARCHAR(20), addressline1 VARCHAR(20), [state] VARCHAR(20),zip VARCHAR(20))
DECLARE @Payment AS VARCHAR(20)
DECLARE @state VARCHAR(20)
SET @state='stateA'
INSERT INTO @table1 (addid, payment) VALUES(1,'payment 1')
INSERT INTO @table1 (addid, payment) VALUES(3,'payment 2')
INSERT INTO @table1 (addid, payment) VALUES(4,'payment 3')
INSERT INTO @table1 (addid, payment) VALUES(5,'payment 4')
INSERT INTO @addresstable (addid, Fname, lname, city, addressline1, [state], zip) VALUES (1, 'A', 'A', 'A', 'A', 'stateA', 'A')
INSERT INTO @addresstable (addid, Fname, lname, city, addressline1, [state], zip) VALUES (2, 'B', 'B', 'B', 'B', 'stateA', 'B')
INSERT INTO @addresstable (addid, Fname, lname, city, addressline1, [state], zip) VALUES (3, 'C', 'C', 'C', 'C', 'stateA', 'C')
INSERT INTO @addresstable (addid, Fname, lname, city, addressline1, [state], zip) VALUES (4, 'D', 'D', 'D', 'D', 'stateB', 'D')
INSERT INTO @addresstable (addid, Fname, lname, city, addressline1, [state], zip) VALUES (5, 'E', 'E', 'E', 'E', 'stateB', 'E')
--Query
SELECT Fname,lname,city, addressline1, state,zip, payment
FROM @addresstable a
LEFT JOIN @table1 t
ON t.addid = a.addid
AND ((payment LIKE + '%' + COALESCE(@Payment,'') + '%' ) OR (payment LIKE + '%all%' ) )
WHERE [state] = @state