IF EXISTS SQL 语句无效

IF EXISTS SQL Statement won't work

我从下面的 T-SQL 查询中得到这个错误。

错误信息:

Msg 102, Level 15, State 1, Line 13 Incorrect syntax near '101'

谁能找出这里的错误在哪里?使用 Management Studio / SQLServerExpress 期望的结果是插入新记录或更新现有记录。

下面是我的查询:

IF EXISTS (SELECT * FROM Product WHERE ProductID = 101) 
UPDATE Product SET  
ProductID = 101 , InsurerID = 1, CategoryID =1, Name = 'Landlord',
[description] ='Allianz Landlord', label = 'NULL', AssumptionRef  ='NULL',
QuoteProviderKey ='A75',AccidentalDamageCover =0, ProductBenefitGroupID = 11,
IsAvailableToBuy =1,IsAvalableToDisplay =0,PercentageContentsCover ='NULL', 
ProductPolicyView ='NULL', ProductFee =NULL 
WHERE ProductID = 101 
ELSE 
INSERT INTO Product 
VALUES 101,1,1,'Landlord','Allianz Landlord','NULL','NULL','A75',0,11,1,0,'NULL','NULL',NULL
WHERE ProductID  = 101

替换最后一个 where 子句,因为根据您的情况,您不需要在 INSERT 语句中使用 where 试试运行这个

IF EXISTS (SELECT * FROM Product WHERE ProductID = 101)  UPDATE Product SET   ProductID = 101 , InsurerID = 1, CategoryID =1, Name = 'Landlord', [description] ='Allianz Landlord', label = 'NULL', AssumptionRef  ='NULL', QuoteProviderKey ='A75',AccidentalDamageCover
=0, ProductBenefitGroupID = 11, IsAvailableToBuy =1,IsAvalableToDisplay =0,PercentageContentsCover ='NULL',  ProductPolicyView ='NULL', ProductFee =NULL  WHERE ProductID = 101  ELSE  INSERT INTO Product  VALUES 101,1,1,'Landlord','Allianz Landlord','NULL','NULL','A75',0,11,1,0,'NULL','NULL',NULL

您的 INSERT 语句有一个设置了 VALUESWHERE 子句,该子句无效:

INSERT INTO Product
VALUES 101
    ,1
    ,1
    ,'Landlord'
    ,'Allianz Landlord'
    ,'NULL'
    ,'NULL'
    ,'A75'
    ,0
    ,11
    ,1
    ,0
    ,'NULL'
    ,'NULL'
    ,NULL
WHERE ProductID = 101

您还遗漏了 VALUES 部分周围的 (),以及列出的列(虽然,这不会出错,但您应该养成明确的习惯列出列)

您的陈述应如下所示:

INSERT INTO Product
(
    ProductID
    ,InsurerID
    ,CategoryID
    ,NAME
    ,[description]
    ,label 
    ,AssumptionRef 
    ,QuoteProviderKey 
    ,AccidentalDamageCover 
    ,ProductBenefitGroupID 
    ,IsAvailableToBuy 
    ,IsAvalableToDisplay 
    ,PercentageContentsCover 
    ,ProductPolicyView 
    ,ProductFee 
)
VALUES 
(
    101
    ,1
    ,1
    ,'Landlord'
    ,'Allianz Landlord'
    ,'NULL'
    ,'NULL'
    ,'A75'
    ,0
    ,11
    ,1
    ,0
    ,'NULL'
    ,'NULL'
    ,NULL
)

另一件要质疑的事情是为什么要使用字符串 'NULL' 值。如果您打算将这些字段设置为 NULL,则它们应该是 NULL 而不是 'NULL'

你忘记了开始结束

IF (.....)
BEGIN

END
ELSE
BEGIN

END