我正在寻找类似于 C# 运算符的功能 ?: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator
我需要根据两个参数在服务器端过滤数据:
-
@CountryIDs - 这是逗号分隔值的列表,例如"27,28,81" - 表示国家 ID 27、国家 ID 28 和国家 ID 81
-
@Keyword匹配客户名称。
有时我不想提供应该选择的国家 ID 的完整列表,而是我希望选择所有内容 - 有点像"."我创建了一个自定义函数"CSV2Table_fn",允许我提供 CSV 列表,如国家 ID。
DECLARE @CountryIDs nvarchar(4000), @Keyword nvarchar(50)
SET @CountryIDs = '25,28,81'
SET @Keyword = null
if (len(@Keyword) > 0) -- search for names matching keyword
begin
SELECT Name, CountryID FROM Company
WHERE CountryID IN (
SELECT DISTINCT ItemValue FROM CSV2Table_fn(
ISNULL((SELECT
CASE WHEN (SELECT COUNT(*) FROM (SELECT DISTINCT ItemValue FROM CSV2Table_fn(@CountryIDs,',')) t) > 0 THEN @CountryIDs
ELSE null
END
),CountryID),',')
)
AND Name LIKE '%' + @Keyword + '%'
end
else -- no keyword provided
begin
SELECT Name, CountryID FROM Company
WHERE CountryID IN (
SELECT DISTINCT ItemValue FROM CSV2Table_fn(
ISNULL((SELECT
CASE WHEN (SELECT COUNT(*) FROM (SELECT DISTINCT ItemValue FROM CSV2Table_fn(@CountryIDs,',')) t) > 0 THEN @CountryIDs
ELSE null
END
),CountryID),',')
)
end
- 编辑:代码现在按预期工作。但是,这不是很干净,可以优化。
做这样的事情吗:
SELECT Name, CountryID
FROM Company
WHERE CHARINDEX(',' + CONVERT(varchar(100), CountryID) + ',', ',' + ISNULL(@CountryIDs, CONVERT(varchar(100), CountryID)) + ',') > 0
AND Name LIKE '%' + ISNULL(@Keyword, '') + '%'
** 编辑得更简单一些,并处理空@CountryIDs参数。
为了允许空和 CSV 像 '123,456,789' 作为@CountryIDs的值传入,我使用了这个:
SELECT Name, CountryID FROM Company
WHERE CountryID IN (
SELECT DISTINCT ItemValue FROM CSV2Table_fn(
ISNULL((SELECT
CASE WHEN (SELECT COUNT(*) FROM (SELECT DISTINCT ItemValue FROM CSV2Table_fn(@CountryIDs,',')) t) > 0 THEN @CountryIDs
ELSE null
END
),CountryID),',')
)