将IF..ELSE与使用子查询的多条INSERT INTO结合使用

时间:2018-11-05 11:22:03

标签: sql-server

我在数据库上有两个通过外键相互关联的表 table1是日记 table2是journalEntries 我有一个查询来检查表日记中当前日期是否有行,是否有记录,然后它将记录插入到journalEntries中 如果为null,则它将在日记表table1上插入记录,然后插入到journalEntries table2

我尝试了不同的方法,但是没有用

if (select j_id from journal where [date] > (SELECT CONVERT(VARCHAR(10),GETDATE(),111))) is null
insert into journal values (getdate() as [date], getdate() as [insert_date], '' as notes)
insert into journalentries (j_id, acc_num, credit, debit, [user_id], note)
select (select (select j_id from Journal where [date] in (SELECT CONVERT(VARCHAR(10),GETDATE(),111))) as j_id, @acc_num, @credit, @debit, @user_id, @note)

else
insert into journalentries (j_id, acc_num, credit, debit, [user_id], note)
select (select j_id from Journal where [date] in (SELECT CONVERT(VARCHAR(10),GETDATE(),111))) as j_id, @acc_num, @credit, @debit, @user_id, @note
end

另一种方式

if(select j_id from journal where [date] in ('2019-01-01')) is null
insert journal([date], insert_date, notes)
OUTPUT inserted.j_id, '2019-01-01', '2019-01-01', ''
INTO dbo.journalentries(j_id, acc_num, credit, debit, [user_id], note)
values (j_id, @acc_num, @credit, @debit, @user_id, @note)
else
select (select j_id from Journal where [date] in (SELECT CONVERT(VARCHAR(10),GETDATE(),111))) as j_id, @acc_num, @credit, @debit, @user_id, @note

2 个答案:

答案 0 :(得分:1)

我使用了scop_identity()并且有效

declare @j_id int = (select j_id from journal where [date] in (SELECT CONVERT(VARCHAR(10),GETDATE(),111)))
if @j_id is null
    begin 
    insert into journal values (getdate(), getdate(), '') set @j_id = SCOPE_IDENTITY(); insert into journalentries (j_id, acc_num, credit, debit, [user_id], note) values (@j_id, @acc_num, @credit, @debit, @user_id, '');
    end 
    else
    begin
    insert into journalentries (j_id, acc_num, credit, debit, [user_id], note)values (@j_id, @acc_num, @credit, @debit, @user_id, '')
    end

答案 1 :(得分:0)

只是一个指针,对评论来说太长了

    if (select j_id from journal where [date] > (SELECT CONVERT(VARCHAR(10),GETDATE(),111))) is null
    begin 
    insert into journal  select getdate() as [date], getdate() as [insert_date], '' as notes;
    --insert into journalentries j_id, acc_num, credit, debit, [user_id], note); '!! where are you selecting this from?
    select (select (select j_id from Journal where [date] in (SELECT CONVERT(VARCHAR(10),GETDATE(),111))) as j_id, @acc_num, @credit, @debit, @user_id, @note);
    end 
    else
    begin
    --insert into journalentries (j_id, acc_num, credit, debit, [user_id], note)  -- !! where are you selecting this from?
    select (select j_id from Journal where [date] in (SELECT CONVERT(VARCHAR(10),GETDATE(),111))) as j_id, @acc_num, @credit, @debit, @user_id, @note
    end