我从此代码中得到一个错误
DECLARE @existingEmail AS INT
SET NOCOUNT ON;
@existingEmail = COUNT(*) AS total FROM table WHERE email = @email;
INSERT INTO table2 (email)
VALUES (CASE WHEN @existingEmail IS 1 THEN 'Yes' ELSE 'No' END);
那是我得到的错误
第15行,状态1,过程sp_counts,第21行,消息[第7行开始]
“ @existingEmail”附近的语法不正确。
答案 0 :(得分:3)
从性能的角度来看,使用COUNT
来检查是否存在并不是最好的主意:
INSERT INTO table2 (email)
SELECT CASE WHEN EXISTS (SELECT 1 FROM table WHERE email = @email) THEN 'Yes'
ELSE 'No' END
答案 1 :(得分:1)
代替此:
@existingEmail = COUNT(*) as total from table where email = @email;
您需要执行以下操作:
SELECT @existingEmail = COUNT(*) as total from table where email = @email;
或者这个:
SET @existingEmail = (SELECT COUNT(*) as total from table where email = @email);
答案 2 :(得分:0)
在您试图设置变量@existingEmail
的那一行中,您缺少关键字set
。如果将该行更新为以下内容,则应该可以解决该错误。
set @existingEmail = (SELECT COUNT(*) from table where email = @email);