我正在尝试在多个数据库中运行一段代码。一列 Mfg_ID 存在于某些表中,但不存在于其他表中。我尝试了 IF EXISTS 语句。当该列不存在时,它会抛出一个错误,就好像它运行了应该跳过的块一样。 (列名称“Mfg_ID”无效。)
显然,SQL 会检查代码是否有效,即使它跳过了那段代码?我该如何解决这个问题?下面的代码....
IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Inv_Dtl_3834' AND COLUMN_NAME = 'Mfg_ID')
BEGIN
BEGIN TRY
SELECT CAST(SUBSTRING(SUBSTRING(DB_NAME(), 3, 255), 1,
CHARINDEX('_', SUBSTRING(DB_NAME() , 3, 255))-1) AS INT) AS
CID,
SUBSTRING(SUBSTRING(DB_NAME(), 3, 255), CHARINDEX('_',
SUBSTRING(DB_NAME() , 3, 255))+1, 255) AS Client,
Vend_Num,
Vend_Name,
Min(InvDate) AS Min_InvDate,
MAX(InvDate) AS Max_InvDate,
Item_Num,
VITEM_Num,
Mfg_ID,
Item_Desc,
SUM(InvQty) AS InvQty,
InvPrice
FROM Inv_Dtl_3834
GROUP BY Vend_Num, Vend_Name, Item_Num, VITEM_Num, Mfg_ID, Item_Desc, InvPrice
END TRY
BEGIN CATCH
END CATCH
END
ELSE
BEGIN
SELECT CAST(SUBSTRING(SUBSTRING(DB_NAME(), 3, 255), 1, CHARINDEX('_',
SUBSTRING(DB_NAME() , 3, 255))-1) AS INT) AS CID,
SUBSTRING(SUBSTRING(DB_NAME(), 3, 255), CHARINDEX('_',
SUBSTRING(DB_NAME() , 3, 255))+1, 255) AS Client,
Vend_Num,
Vend_Name,
Min(InvDate) AS Min_InvDate,
MAX(InvDate) AS Max_InvDate,
Item_Num,
VITEM_Num,
'N/A' AS Mfg_ID,
Item_Desc,
SUM(InvQty) AS InvQty,
InvPrice
FROM Inv_Dtl_3834
GROUP BY Vend_Num, Vend_Name, Item_Num, vITEM_Num, Item_Desc, InvPrice
END
我在有和没有 BEGIN TRY 部分的情况下都运行过这个。我已经删除了代码并将其替换为虚拟代码,例如 SELECT 'The field does not exist' 并且有效。