我正在编写一个存储过程来选择地址。有许多选择参数,但是导致我出现问题的是选择状态。 该国家/地区是必需的,可以有一个或多个国家/地区名称 如果该国家是美国,那么州可以是NULL或一对多的州代码。 我有一个表值函数(ParmTable_String),所以我可以加入参数列表,这在有状态代码时有效:
DECLARE @Country AS varchar(MAX);
DECLARE @State AS varchar(256);
SET @Country = 'USA';
SET @State = 'ME, VT';
SELECT *
FROM Customer
JOIN ParmTable_String(@Country, ',') AS CT
ON Country = CT.str
JOIN ParmTable_String(@State, ',') AS ST
ON State = ST.str
但如果@State = null
我得到一个空结果集。如果我将其设为左连接并添加where子句,则它适用于单个状态代码或null但不适用于列表。
WHERE State = @State OR @State IS NULL
任何人都有解决方案吗?
好的我有一个解决方案,但我认为有更好的方法,因为这对我来说似乎有点粗糙:
DECLARE @Country AS varchar(MAX);
DECLARE @State AS varchar(256);
SET @Country = 'USA';
SET @State = 'ME, VT';
SELECT *
FROM Customer
JOIN ParmTable_String(@Country, ',') AS CT
ON Country = CT.str
WHERE (State IN
(SELECT str from lntw.ParmTable_String(@State, ',')) OR @State IS NULL)
答案 0 :(得分:0)
我对sql server并不熟悉,但我想知道这样的事情是否可行
State = NULLIF(@State,State)
**我假设NULLIF等同于oracles nvl()函数
答案 1 :(得分:0)
如果ST.str为空字符串,则NULLIF(ST.str,'')将返回null。然后你尝试做State = NULL,它不会返回记录。
试试这个,它应该返回客户记录,无论是否有匹配的状态:
DECLARE @Country AS varchar(MAX);
DECLARE @State AS varchar(256);
SET @Country = 'USA';
SET @State = 'ME, VT';
SELECT *
FROM Customer
JOIN ParmTable_String(@Country, ',') AS CT
ON Country = CT.str
JOIN ParmTable_String(isnull(@State,''), ',') AS ST
ON (State = ST.str or State is null)
答案 2 :(得分:0)
你有一个OR ...为什么不尝试两个查询:
IF @State is null
BEGIN
SELECT * FROM Customer
JOIN ParmTable_String(@Country, ',') AS CT
ON Country = CT.str
END
ELSE
BEGIN
SELECT * FROM Customer
JOIN ParmTable_String(@Country, ',') AS CT
ON Country = CT.str
JOIN ParmTable_String(@State, ',') AS ST
ON State = ST.str
END
答案 3 :(得分:0)
怎么样
DECLARE @Country AS varchar(MAX);
DECLARE @State AS varchar(256);
SET @Country ='USA';
SET @State ='ME,VT';
SELECT *
来自客户
加入ParmTable_String(@ Country,',')AS CT
ON国家= CT.str
LEFT JOIN ParmTable_String(isNULL(@ State,''),',')AS ST
ON状态= ST.str