Microsoft SQL Server 2012:如何将记录插入关系表

时间:2013-03-17 09:51:19

标签: .net sql sql-server-2012

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

我需要插入一个新日志: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

非常感谢你。

1 个答案:

答案 0 :(得分:2)

您可以创建一个VIEW,一个INSTEAD OF INSERT触发器并运行一个INSERT - 语句。

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)