我正在使用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为真时才执行。
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:2)
检查现有列的另一种方法
IF COL_LENGTH('dbo.ServerSettings', 'MapIsAlwayCalcLenByWebServices') IS NOT NULL
EXEC ('UPDATE dbo.ServerSettings
SET MapCalculateDistanceSource = 0
WHERE MapIsAlwayCalcLenByWebServices = 0')