我正在寻找类似于C#运算符的功能?:http://msdn.microsoft.com/en-US/library/ty67wk28(v=vs.80)
我需要根据两个参数过滤服务器端的数据:
@CountryIDs - 这是逗号分隔值的列表,例如'27,28,81' - 意为CountryID 27,CountryID 28和CountryID 81
@Keyword以匹配客户名称。
有时我不想提供应该选择的CountryID的完整列表,而是我想要选择所有内容 - 有点像“。” 我创建了一个自定义函数“CSV2Table_fn”,它允许我提供CSV的列表,如CountryIDs。
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
答案 0 :(得分:1)
你可以这样做:
SELECT Name, CountryID
FROM Company
WHERE CHARINDEX(',' + CONVERT(varchar(100), CountryID) + ',', ',' + ISNULL(@CountryIDs, CONVERT(varchar(100), CountryID)) + ',') > 0
AND Name LIKE '%' + ISNULL(@Keyword, '') + '%'
**编辑有点简单并处理null @CountryIDs param。
答案 1 :(得分:0)
为了允许null和像'123,456,789'这样的CSV作为@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),',')
)