在特殊请求运行中,我需要更新sql server 2012数据库中的Locker
和Lock
表,我有以下2个表定义:
CREATE TABLE [dbo].[Locker](
[lockerID] [int] IDENTITY(1,1) NOT NULL,
[schoolID] [int] NOT NULL,
[number] [varchar](10) NOT NULL,
[lockID] [int] NULL
CONSTRAINT [PK_Locker] PRIMARY KEY NONCLUSTERED
(
[lockerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY =
OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 97)
ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[Lock](
[lockID] [int] IDENTITY(1,1) NOT NULL,
[schoolID] [int] NOT NULL,
[comboSeq] [tinyint] NOT NULL
CONSTRAINT [PK_Lock] PRIMARY KEY NONCLUSTERED
(
[lockID] ASC
)
Locker
表是主表,Lock
表是辅助表。我需要添加500个新的Locker
个号码,用户已将这些号码放在Locker
表格中,并由LockerID
唯一定义。我还需要在相应的Lock
表中添加500个新行,该表在Lock
表中唯一定义并由lockid
标识。
由于lockid
是lock
表中的键值,并且在locker
表中唯一定义,因此我想知道如何更新lock
表500新行。然后,我想取lockid
的值(从lock
表中获取已创建的500个新行),并将这500个lockids
唯一地唯一放入为该行创建的500行中。 lock
表。
到目前为止,我的sql看起来如下:
declare @SchoolID int = 999
insert into test.dbo.Locker ( [schoolID], [number])
select distinct LKR.schoolID, A.lockerNumber
FROM [InputTable] A
JOIN test.dbo.School SCH
ON A.schoolnumber = SCH.type
and A.schoolnumber = @SchoolNumber
JOIN test.dbo.Locker LKR
ON SCH.schoolID = LKR.schoolID
AND A.lockerNumber not in (select number
from dbo.Locker
where schoolID = @SchoolID)
order by LKR.schoolID, A.lockerNumber
我不确定如何完成将lockerid
唯一地放入lock
和locker
表的其余任务?因此,你可以修改我刚才列出的和/或
想出一些新的SQL,它会告诉我如何实现我的目标?
答案 0 :(得分:0)
您应该使用OUTPUT
声明。首先,您应该将行添加到锁定表然后添加克数锁定并准备插入到锁定表。这符合你的期望:
DECLARE @tmp TABLE (lockid INT)
INSERT dbo.Lock
( schoolID, comboSeq )
OUTPUT Inserted.lockID INTO @tmp ( lockid )
(SELECT
999,
1
FROM master..spt_values sv WHERE sv.type = 'P' AND sv.number <= 500);
INSERT INTO dbo.Locker( schoolID, number, lockID )
SELECT x.schoolID, x.lockerNumber, y.lockid
FROM
(
SELECT TOP 100 PERCENT DISCTINCT LKR.schoolID, A.lockerNumber, ROW_NUMBER() OVER (ORDER BY A.LockerNumber) rn
FROM [InputTable] A
JOIN test.dbo.School SCH ON A.schoolnumber = SCH.type
and A.schoolnumber = @SchoolNumber
JOIN test.dbo.Locker LKR ON SCH.schoolID = LKR.schoolID
AND A.lockerNumber not in (select number from dbo.Locker
WHERE schoolID = @SchoolID)
ORDER by LKR.schoolID, A.lockerNumber ) x
JOIN (SELECT t.lockid, ROW_NUMBER() OVER (ORDER BY t.lockid) AS rn FROM @tmp t
) y
ON x.rn = y.rn