我想比较两个字符串,我写了这段代码:
...
...
Declare @LTN as nvarchar(MAX);
SELECT @LTN = LicenceTypesNames
FROM tbLicence
WHERE LicenceType = @LicenceType
IF @LTN != @LicenceTypesNames
DELETE FROM tbCompanyAgent
WHERE LicenceNumber IN (SELECT DISTINCT LicenceNumber
FROM tbLicence
WHERE LicenceType = @LicenceType)
INSERT INTO [dbo].[tbLicence]( ...)
ELSE
INSERT INTO [dbo].[tbLicence](...)
请注意,@LTN
包含类似“Property& Casualty,Life”的字符串
和@LicenceTypesNames包含类似“Life”的字符串。
在这种情况下,它应该执行插入和删除操作 如果两者相等,那么它应该只执行插入操作。
上面的代码没有正确检查条件!!!
请帮助!!!
答案 0 :(得分:0)
问题是在IF
之后,只有一个语句会有条件地执行,除非添加BEGIN....END
块。
所以在你的情况下:
IF @LTN != @LicenceTypesNames
DELETE FROM tbCompanyAgent
WHERE LicenceNumber IN (SELECT DISTINCT LicenceNumber
FROM tbLicence
WHERE LicenceType = @LicenceType)
INSERT INTO [dbo].[tbLicence]( ...)
ELSE
INSERT INTO [dbo].[tbLicence](...)
仅 DELETE
取决于您IF
检查 - 但第一个INSERT
将始终执行!
您需要将其更改为:
IF @LTN != @LicenceTypesNames
BEGIN -- ADD THIS!!
DELETE FROM tbCompanyAgent
WHERE LicenceNumber IN (SELECT DISTINCT LicenceNumber
FROM tbLicence
WHERE LicenceType = @LicenceType)
INSERT INTO [dbo].[tbLicence]( ...)
END -- ADD THIS!!
ELSE
INSERT INTO [dbo].[tbLicence](...)
得到我认为你想做的事情......