简体   繁体   中英

Microsoft SQL Server 2012: How to Insert record into relational tables

is there a way to insert a record into relational tables and not to run query for each table?

I need to insert a new log: l_WinUser, l_Status, t_StartTime, t_StartDate where username = username, g_Exe = g_Exe

And if so is there a way in .NET to get the inserted record ID? Currently I am executing another query to retrieve the inserted log (works fine):

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

Here's the ERD:

ERD

Thank you so much.

You can create a VIEW, an INSTEAD OF INSERT Trigger and run one INSERT -Statement against it.

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 

Now you insert your new entry like this

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

You will get the new l_LogID using

select SCOPE_IDENTITY()

NOTE: In the first attempt I wrote that an INSERT against a view would also insert/update related tables, which is not true. So I corrected this answer.

And here's the trigger (untested):

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM