In a t-sql 2012, I want to place the new lockid values obtain from the first insert statement (for the lock table) indiviudally into the second insert statement (locker table in the in the column called lockid).
See sql below.
insert into [dbo].[Lock]
SELECT 134,c.serialNumber,c.type,2
FROM .[dbo].[Lock] c
join [dbo].[Locker] locker on locker.lockID = c.lockID
AND locker.locationID between 1552 and 1555
order by locationID, number
insert into [dbo].[Locker]
SELECT
134
,[number]
,[serialNumber]
,[type]
,[locationID]
,[grade]
,[reserved]
,[lockID] --want new values from lock table
,[share]
,[lockType]
FROM [dbo].[Locker]
where [schoolID] = 12 and locationID between 1552 and 1555
I would like to use something like the sql listed below to insert the lockid values from
the lock table into the locker table for the column called lockid.
with cte as
(
Select SchoolID, lockID,
Row_Number() Over(Partition by SchoolID order by LockerID) RowNum
From Locker
)
Update cte set
lockID = RowNum + 117173
where SchoolID = 134;
The problem is the lockid column of the locker table has a foreign key constraint on the lockid column of the lock tabe.
There is nothing setup for 'cascade updates'.
Thus could you show me the sql on how I can do the insert on the locker table with obtaining the lockid values from the lock table without needing to do a drop or disable index?
If this is not possible, would you show me the sql on how to accomplish my goals using the disable, drop index, and other whatever way you think is a good solution?
Here is a definition of the 2 tables:
USE [TEST]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Locker](
[lockerID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[schoolID] [int] NOT NULL,
[number] varchar NOT NULL,
[serialNumber] varchar NULL,
[type] varchar NULL,
[locationID] [int] NULL,
[grade] varchar NULL,
[reserved] [bit] NULL,
[lockID] [int] NULL,
[share] [bit] NULL,
[lockType] varchar 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]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Locker] WITH NOCHECK ADD CONSTRAINT [FK_Locker_Lock] FOREIGN KEY([lockID])
REFERENCES [dbo].[Lock] ([lockID])
GO
ALTER TABLE [dbo].[Locker] CHECK CONSTRAINT [FK_Locker_Lock]
GO
USE [TEST]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Lock](
[lockID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[schoolID] [int] NOT NULL,
[serialNumber] varchar NULL,
[type] varchar NULL,
[comboSeq] [tinyint] NOT NULL,
CONSTRAINT [PK_Lock] PRIMARY KEY NONCLUSTERED
(
[lockID] 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]
GO
SET ANSI_PADDING OFF
GO