搜索存储过程无法按预期工作

时间:2017-07-28 10:20:06

标签: c# sql-server stored-procedures

我写了一个CTE,它返回了一些列

;WITH  cteResult AS
                (
                    SELECT distinct
                            I.CUSTOMER,
                            I.OFFICE,
                            I.Column1 + ' ' + I.Column2 AS ADDRESS,
                            I.POSTCODE AS ZIPCODE  
                    FROM 
                        MYTABLE I WITH (NOLOCK)
                )

我根据下面给出的条件筛选返回的列:

    SELECT 
            CUSTOMER,
            OFFICE,
            ADDRESS,
            ZIPCODE   
        FROM 
            cteResult AS CR WITH (NOLOCK)
        WHERE       
            (@pstrCustId IS NULL OR (CR.CUSTOMER = @pstrCustId))
AND 
            (@pstrAddress IS NULL OR (CR.ADDRESS = @pstrAddress))
        AND 
            (@pstrPostcode IS NULL OR (CR.ZIPCODE = @pstrPostcode))

当我通过替换上面的选择查询中的@pstrCustId='1234'来测试时,它会返回除custIds以外的结果 '1234'但是当我评论"@pstrCustId IS NULL OR"部分时,它会返回正确的结果'即只有custId='1234'的结果。

我之前写过类似的存储过程,但它工作正常。但是,这个特定的SP没有。

任何建议。

4 个答案:

答案 0 :(得分:1)

为什么要返回带有所需id的结果或者如果没有指定? 这有什么不对吗?:

SELECT 
    CUSTOMER,
    OFFICE,
    ADDRESS,
    ZIPCODE   
FROM 
    cteResult AS CR WITH (NOLOCK)
WHERE       
    (CR.CUSTOMER = @pstrCustId)

答案 1 :(得分:0)

如果@pstrCustId为NULL,或许你想要返回所有内容。

在那种情况下。

使用(按照之前的回答)

if (@pstrCustId IS NULL) 
BEGIN
    SELECT distinct
                        I.CUSTOMER,
                        I.OFFICE,
                        I.Column1 + ' ' + I.Column2 AS ADDRESS,
                        I.POSTCODE AS ZIPCODE  
                FROM 
                    MYTABLE I WITH (NOLOCK)
END
ELSE
BEGIN
    SELECT distinct
                        I.CUSTOMER,
                        I.OFFICE,
                        I.Column1 + ' ' + I.Column2 AS ADDRESS,
                        I.POSTCODE AS ZIPCODE  
                FROM 
                    MYTABLE I WITH (NOLOCK)
    WHERE       
        (I.CUSTOMER = @pstrCustId)
    END

答案 2 :(得分:0)

当他们没有过滤器值并更改你的where子句时,检查所有变量是否为空:

WHERE       
    CR.CUSTOMER = ISNULL(@pstrCustId, CR.CUSTOMER)
    AND
    CR.ADDRESS = ISNULL(@pstrAddress, CR.ADDRESS)
    AND
    CR.ZIPCODE = ISNULL(@pstrPostcode, CR.ZIPCODE)

答案 3 :(得分:0)

为什么不使用动态SQL?它还有助于优化运行时间。首先将CTE的结果插入到临时表中,然后动态sql应该做到这一点。

;WITH cteResult as
(
    SELECT DISTINCT
        I.CUSTOMER,
        I.OFFICE,
        I.Column1 + ' ' + I.Column2 AS ADDRESS,
        I.POSTCODE AS ZIPCODE  
    FROM 
        MYTABLE I WITH (NOLOCK)
)
SELECT * INTO #TempTable FROM cteResult A

SET @DynamicSQL = 'SELECT CUSTOMER, OFFICE, ADDRESS, ZIPCODE FROM #TempTable AS CR WITH (NOLOCK) WHERE 1 = 1
    ' + (CASE WHEN @pstrCustId IS NULL THEN '' ELSE ' AND CR.CUSTOMER = ''' + @pstrCustId END) + '''
    ' + (CASE WHEN @pstrAddress IS NULL THEN '' ELSE ' AND CR.ADDRESS = ''' + @pstrAddress END) + '''
    ' + (CASE WHEN @pstrPostcode IS NULL THEN '' ELSE ' AND CR.ZIPCODE = ''' + @pstrPostcode END) + ''''

EXEC SP_EXECUTESQL @DynamicSQL