2

我正在使用 Microsoft SQL Server。

IF EXISTS (
    SELECT *
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'ServerSettings'
        AND COLUMN_NAME = 'MapIsAlwayCalcLenByWebServices'
)
    IF (
        SELECT MapIsAlwayCalcLenByWebServices
        FROM ServerSettings
    ) = 0
        UPDATE ServerSettings
        SET MapCalculateDistanceSource = 0

有谁知道为什么这段代码会抛出错误“无效的列名”。我认为第二个选择仅在第一个 if 为真时执行。

4

3 回答 3

7

不,首先编译整个批处理,然后开始执行。由于您引用无效列而无法编译批处理,因此它永远不会执行该if语句。

您需要保护引用 中可能不存在的列的代码,EXEC例如:

if exists(select * from INFORMATION_SCHEMA.COLUMNS 
          where TABLE_NAME = 'ServerSettings' and
                COLUMN_NAME = 'MapIsAlwayCalcLenByWebServices')
begin
    exec('UPDATE ServerSettings SET MapCalculateDistanceSource = 0
          WHERE MapIsAlwayCalcLenByWebServices = 0')
end

于 2013-08-28T06:57:29.917 回答
3

试试这个——

IF EXISTS(
    SELECT 1 
    FROM sys.columns c 
    WHERE c.name = 'MapIsAlwayCalcLenByWebServices'
        AND c.[object_id] = OBJECT_ID('dbo.ServerSettings')
) BEGIN

        EXEC sys.sp_executesql '
        UPDATE dbo.ServerSettings
        SET MapCalculateDistanceSource = 0
        WHERE MapIsAlwayCalcLenByWebServices = 0'

END
于 2013-08-28T06:58:02.283 回答
2

检查现有列的另一种方法

IF COL_LENGTH('dbo.ServerSettings', 'MapIsAlwayCalcLenByWebServices') IS NOT NULL
EXEC ('UPDATE dbo.ServerSettings
       SET MapCalculateDistanceSource = 0
       WHERE MapIsAlwayCalcLenByWebServices = 0')
于 2013-08-28T07:42:36.493 回答