我有以下IF
块,只有当我的表为空时才会执行该块。但它似乎是在BEGIN
和END
之间执行代码,即使我的表有一行。
IF ((SELECT COUNT(*) FROM [dbo].[KeyProperties]) = 0)
BEGIN
INSERT INTO [dbo].[KeyProperties] (KeyId,PropertyId) VALUES
((SELECT Id FROM [dbo].[Keys] WHERE Priority=1),(SELECT Id FROM [dbo].[Properties] WHERE Name='SocialSecurityNumber'))
INSERT INTO [dbo].[KeyProperties] (KeyId,PropertyId) VALUES
((SELECT Id FROM [dbo].[Keys] WHERE Priority=2),(SELECT Id FROM [dbo].[Properties] WHERE Name='FirstName')),
((SELECT Id FROM [dbo].[Keys] WHERE Priority=2),(SELECT Id FROM [dbo].[Properties] WHERE Name='LastName')),
((SELECT Id FROM [dbo].[Keys] WHERE Priority=2),(SELECT Id FROM [dbo].[Properties] WHERE Name='Email'))
END
上面的代码抛出了这个错误:
无法将值NULL插入列' KeyId',表中 ' MYDATABASE.dbo.KeyProperties&#39 ;;列不允许空值。插入 失败。该语句已终止。端
答案 0 :(得分:5)
1)使用NOT EXISTS
而不是计数和比较0
2)使用INSERT INTO tab(col) SELECT
IF NOT EXISTS (SELECT 1 FROM [dbo].[KeyProperties])
BEGIN
INSERT INTO [dbo].[KeyProperties] (KeyId,PropertyId)
SELECT
(SELECT Id FROM [dbo].[Keys] WHERE Priority=1),
(SELECT Id FROM [dbo].[Properties] WHERE Name='SocialSecurityNumber');
INSERT INTO [dbo].[KeyProperties] (KeyId,PropertyId)
SELECT
(SELECT Id FROM [dbo].[Keys] WHERE Priority=2),
(SELECT Id FROM [dbo].[Properties] WHERE Name='FirstName')
UNION ALL
SELECT
(SELECT Id FROM [dbo].[Keys] WHERE Priority=2),
(SELECT Id FROM [dbo].[Properties] WHERE Name='LastName'),
UNION ALL
SELECT
(SELECT Id FROM [dbo].[Keys] WHERE Priority=2),
(SELECT Id FROM [dbo].[Properties] WHERE Name='Email');
END
答案 1 :(得分:2)
改为使用变量:
DECLARE @Count INT
(SELECT @Count = COUNT(*) FROM [dbo].[KeyProperties])
IF (@Count = 0)
或只是
IF NOT EXISTS (SELECT TOP 1 NULL FROM [dbo].[KeyProperties])
答案 2 :(得分:0)
尝试不存在于下面
IF Not Exists(SELECT 1 FROM [dbo].[KeyProperties])
BEGIN
INSERT INTO [dbo].[KeyProperties] (KeyId,PropertyId) VALUES
((SELECT Id FROM [dbo].[Keys] WHERE Priority=1),(SELECT Id FROM [dbo].[Properties] WHERE Name='SocialSecurityNumber'))
INSERT INTO [dbo].[KeyProperties] (KeyId,PropertyId) VALUES
((SELECT Id FROM [dbo].[Keys] WHERE Priority=2),(SELECT Id FROM [dbo].[Properties] WHERE Name='FirstName')),
((SELECT Id FROM [dbo].[Keys] WHERE Priority=2),(SELECT Id FROM [dbo].[Properties] WHERE Name='LastName')),
((SELECT Id FROM [dbo].[Keys] WHERE Priority=2),(SELECT Id FROM [dbo].[Properties] WHERE Name='Email'))
END