我可以在where语句中自我更新

时间:2017-07-14 09:27:32

标签: sql sql-server tsql

我有一个程序,它从另一个表的列中获取语句。我想添加一个特定的条件,仅用于第一次执行语句,而不添加任何额外的行/表/列。所以我想把声明设置为

tblBill.sdApprovedDate > dateadd(month,-3,getdate()) and 
(update tblInvoiceConfig 
set vcWhereSQL = 'tblBill.chBillStatus = ''A'' ' 
where intID = 7)

但是我得到一个错误,说更新不是bool表达。
我有两个问题

a)我可以以某种方式使这个更新成为一个布尔表达式

b)这样的查询是否会正确执行(例如,第一次条件的日期必须不小于3个月,之后的每次执行都只会检查chBillStatus)

编辑: 有人问,使用此值的部分程序

SET @nvcSQLQuery = '
SELECT DISTINCT top 3
tblBill.intBillID, 
(... a lot of other stuff ..)
FROM 
(...)
WHERE
' + SELECT vcWhereSQL from tblInvoiceConfig where intID = 7 + '
(...)'

print @nvcSQLQuery
INSERT INTO @result
EXECUTE sp_executeSQL   @nvcSQLQuery,
                        @nvcSQLParams, 
                        @pvcArchiveType = @pvcArchiveType

1 个答案:

答案 0 :(得分:0)

您不需要更新表格,将条件添加到查询中,如下所示:

    SET @nvcSQLQuery = '
    SELECT DISTINCT top 3 t.intBillID
    FROM (
        SELECT
        tblBill.intBillID, 
        (... a lot of other stuff ..)
        FROM 
        (...)
        WHERE 
        tblBill.sdApprovedDate > dateadd(month,-3,getdate()) and
        tblBill.chBillStatus = ''A'' AND

        ' + SELECT vcWhereSQL from tblInvoiceConfig where intID = 7 + '
        (...)

        UNION ALL

        SELECT
        tblBill.intBillID, 
        (... a lot of other stuff ..)
        FROM 
        (...)
        WHERE 
        tblBill.sdApprovedDate <= dateadd(month,-3,getdate()) and   
        ' + SELECT vcWhereSQL from tblInvoiceConfig where intID = 7 + '
        (...)
    )t
'

    print @nvcSQLQuery
    INSERT INTO @result
    EXECUTE sp_executeSQL   @nvcSQLQuery,
                            @nvcSQLParams, 
                            @pvcArchiveType = @pvcArchiveType

或者像这样:

SET @nvcSQLQuery = '
    SELECT
    tblBill.intBillID, 
    (... a lot of other stuff ..)
    FROM 
    (...)
    WHERE 
    ((tblBill.sdApprovedDate > dateadd(month,-3,getdate()) and
    tblBill.chBillStatus = ''A'')
    OR tblBill.sdApprovedDate <= dateadd(month,-3,getdate()))

    AND

    ' + SELECT vcWhereSQL from tblInvoiceConfig where intID = 7 + '
    (...)
'

    print @nvcSQLQuery
    INSERT INTO @result
    EXECUTE sp_executeSQL   @nvcSQLQuery,
                            @nvcSQLParams, 
                            @pvcArchiveType = @pvcArchiveType