0

有没有办法将记录插入关系表而不是对每个表运行查询?

我需要插入一个新日志: l_WinUser, l_Status, t_StartTime, t_StartDate 其中 username = username, g_Exe = g_Exe

如果是这样,.NET 中有没有办法获取插入的记录 ID?目前我正在执行另一个查询来检索插入的日志(工作正常):

SELECT TOP (1) Logs.l_LogID 
FROM Logs 
INNER JOIN Game ON Logs.g_GameID = Game.g_GameID 
INNER JOIN Member ON Logs.m_MemberID = Member.m_MemberID 
WHERE (Game.g_Exe = @exe) 
AND (Member.m_Username = @username) 
AND (Logs.l_WinUser = @winUser)
ORDER BY Logs.l_LogID DESC

这是ERD:

erd

太感谢了。

4

1 回答 1

2

您可以创建一个 VIEW、一个 INSTEAD OF INSERT 触发器并INSERT针对它运行一个 -Statement。

create View View_Logs 
as
select l_WinUser, 
       l_Status, 
       t_StartTime, 
       1t_StartDate,
       username,
       g_Exe
FROM Logs 
INNER JOIN Game ON Logs.g_GameID = Game.g_GameID 
INNER JOIN Member ON Logs.m_MemberID = Member.m_MemberID 

现在你像这样插入你的新条目

insert into View_logs
  (l_WinUser,l_status, lt_StartDate,username,g_exe)
values
  ('Foo', 1, GetDate(),'BarUser','SomeEXE')

你会得到新的l_LogID使用

select SCOPE_IDENTITY()

注意:在第一次尝试中,我写道,针对视图的 INSERT 也会插入/更新相关表,这是不正确的。所以我更正了这个答案。

这是触发器(未经测试):

create trigger YourTriggerName on View_ogs
for instead of insert 
as
declare @GameID int, @MemberID int, @timeKey int

select @GameID=g_GameID from Game g join inserted i on g.g_Exe = i.g_exe
if @GameID is null begin
  insert into Game (g_exe) select g_exe from Inserted
  select @GameID = SCOPE_IDENTITY()
  end

select @MemberID=m.m_memberID from Member m join inserted i on m_username = i.username
if @MemberID is null begin
  insert into Member (m_username) select username from Inserted
  select @MemberID = SCOPE_IDENTITY()
  end

select @timeKey=t.t_timeKey 
from Time_Date t 
     join inserted i 
       on t.t_StartTime=i.t_StartTime 
      and t.t_StartDate = t_StartDate

if @timeKey is null begin
  insert into Time_Date (t_StartTime, t_StartDate) select t_StartTime, t_StartDate from Inserted
  select @timeKey = SCOPE_IDENTITY()
  end

set nocount off
insert into Logs
  (l_WinUser, l_Status, m_MemberID, g_GameID, t_TimeKey)
  select l_WinUser, l_Status, @MemberID, @GameID, @timekey)
于 2013-03-17T10:24:08.353 回答