TSQL ?:操作员功能

时间:2012-07-04 14:52:03

标签: tsql constructor

我正在寻找类似于C#运算符的功能?:http://msdn.microsoft.com/en-US/library/ty67wk28(v=vs.80

我需要根据两个参数过滤服务器端的数据:

  1. @CountryIDs - 这是逗号分隔值的列表,例如'27,28,81' - 意为CountryID 27,CountryID 28和CountryID 81

  2. @Keyword以匹配客户名称。

  3. 有时我不想提供应该选择的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
    
    • 编辑:代码现在按原样运行。然而,这不是很干净,可能会进行优化。

2 个答案:

答案 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),',') 
    )