我的If声明不起作用

时间:2017-01-31 15:07:20

标签: sql sql-server

我尝试使用基于数据库中当前记录的sql if语句,代码为:

if((Select distinct STUDENT_ID, FLAG, YEAR From EF_STUDENTFLAGS Where STUDENT_ID = '100143795' and YEAR = '16/17').ROW_NUMBER <1)

INSERT INTO EF_STUDENTFLAGS (STUDENT_ID, FLAG, YEAR, COMMENTS, LOGGED_BY, SUBDATE, START_DATE, END_DATE) VALUES ('100143795','Safeguarding','16/17','Test','rhewitson','2014-09-03','2017-02-01','2017-02-01')

else

Update EF_STUDENTFLAGS Set COMMENTS = 'Test', LOGGED_BY = 'rhewitson', SUBDATE = '2014-09-03', START_DATE = '2017-02-01', END_DATE = '2017-02-01' Where STUDENT_ID = '100143795' and YEAR = '16/17'

我得到的错误信息是:

  

当EXISTS没有引入子查询时,只能在选择列表中指定一个表达式。

我做错了什么?

编辑:

如果我的数据库中已经有一个记录与我输入的学生ID,标志和年份相同,我希望它创建一个,如果它确实存在,我希望它更新当前记录以反映最新版本

1 个答案:

答案 0 :(得分:1)

试试这个:

if Not Exists(Select top 1 1 From EF_STUDENTFLAGS Where STUDENT_ID = '100143795' and YEAR = '16/17')
    INSERT INTO EF_STUDENTFLAGS (STUDENT_ID, FLAG, YEAR, COMMENTS, LOGGED_BY, SUBDATE, START_DATE, END_DATE) VALUES ('100143795','Safeguarding','16/17','Test','rhewitson','2014-09-03','2017-02-01','2017-02-01')
else
    UPDATE EF_STUDENTFLAGS Set COMMENTS = 'Test', LOGGED_BY = 'rhewitson', SUBDATE = '2014-09-03', START_DATE = '2017-02-01', END_DATE = '2017-02-01' Where STUDENT_ID = '100143795' and YEAR = '16/17'