How to properly create table with 3 columns as primary key? - sql

I have been working with SQL for 3 month, I would like to know create a table with 3 columns as primary key, Any help would be great thank you.
This code below is a Scrip to Create table generated my SQL Server Management Studio of the table
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[REP]
(
[id] [UNIQUEIDENTIFIER] ROWGUIDCOL NOT NULL,
[id_client] [NCHAR](30) NULL,
[id_representant] [UNIQUEIDENTIFIER] NULL,
[date_debut] [DATE] NULL,
[date_fin] [DATE] NULL,
CONSTRAINT [PK_REP]
PRIMARY KEY CLUSTERED ([id] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[REP]
ADD CONSTRAINT [DF_REP_id] DEFAULT (NEWID()) FOR [id]
GO

First all the columns that are part of the primary key have to be not null.
then defining the key just add all columns as comma separated list.
CREATE TABLE [dbo].[REP](
[id] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[id_client] [nchar](30) NOT NULL,
[id_representant] [uniqueidentifier] NULL,
[date_debut] [date] NULL,
[date_fin] [date] NULL,
CONSTRAINT [PK_REP] PRIMARY KEY CLUSTERED
( [id] ASC,id_client ASC )
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
In the code above I changed the column id_client to be not null and added it to the definition of the primary key ... ([id] ASC, id_client ASC).

To add more columns to a primary Key contraint you'd add the additional fields after the first field.
[id] ASC, nextfield ASC, nextfield2 asc

You can have a one composite key that comprise of more than one primary key.
CREATE TABLE xyz (
primary key (id,id_client,id_representer)
);

Related

Insert data to column which has two relationships

So, what I want to do in here is I want to insert the data to table1 who has 'username' field, and this 'username' field has two relationships, which is go to student table and teacher table. But, when I insert the data to user table, I have a problem, and the problem caused by this 'username' field. It caused because the data of 'username' field is not the same as a unique key in student table, and when I change it and made the data same, I get an error too, but this time the data is not the same as a unique in teacher table. So, is it possible to make this 'username' field just get one of the table, like if one of student table and teacher table's data is in 'username', it still can be used. Or maybe this is wrong because of bad ERD? Here's my ERD, if you're asking it:
And well, I know this is really, really bad idea but I made the name in teacher table and student table become a unique key, because I can't create foreign key if I didn't do that. Please, I'm really thankful to your answer.
Here's the ddl for that 3 tables :
Student table :
CREATE TABLE [dbo].[student](
[studentid] [int] IDENTITY(2016000001,1) NOT NULL,
[name] [varchar](50) NOT NULL,
[address] [text] NOT NULL,
[gender] [varchar](7) NOT NULL,
[dateofbirth] [date] NOT NULL,
[nohp] [varchar](13) NOT NULL,
CONSTRAINT [PK_student] PRIMARY KEY CLUSTERED
(
[studentid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IX_student] UNIQUE NONCLUSTERED
(
[name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Teacher Table :
CREATE TABLE [dbo].[teacher](
[teacherid] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NOT NULL,
[gender] [varchar](7) NOT NULL,
CONSTRAINT [PK_teacher] PRIMARY KEY CLUSTERED
(
[teacherid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IX_teacher] UNIQUE NONCLUSTERED
(
[name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
User table:
CREATE TABLE [dbo].[user](
[userid] [int] IDENTITY(1,1) NOT NULL,
[username] [varchar](50) NOT NULL,
[password] [varchar](20) NOT NULL,
[role] [varchar](10) NOT NULL,
CONSTRAINT [PK_user] PRIMARY KEY CLUSTERED
(
[userid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[user] WITH CHECK ADD CONSTRAINT [FK_user_student] FOREIGN KEY([username])
REFERENCES [dbo].[student] ([name])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[user] CHECK CONSTRAINT [FK_user_student]
GO
ALTER TABLE [dbo].[user] WITH CHECK ADD CONSTRAINT [FK_user_teacher] FOREIGN KEY([username])
REFERENCES [dbo].[teacher] ([name])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[user] CHECK CONSTRAINT [FK_user_teacher]
GO
The main issue you faced is because your data structure was less than ideal. It did things like prevent you from changing somebody's name. I tossed together a quick example of a cleaner design. There are many assumptions here. I assumed that people have both a first and last name. I would be remiss if I didn't at least point out that assumption is not something you can always make. https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/ But for a school project it is more than sufficient. I also made the assumption that the addresses are US addresses. Again, this would not work in many real world scenarios. And the last assumption is that everybody can be either Male or Female. In the world today this is not always the case but demonstrates the technique well enough.
Here is how I would probably do this type of design. I would suggest you not just blindly copy this but use it as an idea to get your design more properly normalized.
create table Users
(
UserID int identity not null
, FirstName varchar(50) not null
, LastName varchar(50) not null
, AddressLine1 varchar(50)
, AddressLine2 varchar(50)
, City varchar(50)
, ST char(2)
, ZipCode varchar(9)
, Gender char(1)
, constraint PK_Users primary key clustered
(
UserID
)
, constraint CHK_Users_Gender
CHECK (Gender in ('M', 'F'))
, constraint CHK_Users_ZipCode
CHECK (LEN(ZipCode) in (5,9)) --This ensures you have either the 5 or 9 digiti zip code
)
create table Student
(
StudentID int identity not null
, UserID int not null
, BirthDate date
, constraint PK_Student primary key clustered
(
StudentID
)
, constraint FK_Student_Users foreign key (UserID) references Users(UserID)
)
create table Teacher
(
TeacherID int identity not null
, constraint PK_Teacher primary key clustered
(
TeacherID
)
, constraint FK_Teacher_Users foreign key (TeacherID) references Users(UserID)
)

How I can change the incerement value of cloumn

I have a table and have a lot of records and i can't drop and recreate it
I need to change the increment value of the Id column to 2 the old value is 1
this is an example of the table I need to change the identity increment of
CREATE TABLE [dbo].[RELATED](
[Id] [int] IDENTITY(1,1) NOT NULL,
[RELATEDDESC] [nvarchar](50) NOT NULL,
[USER_ID] [int] NULL,
[ALTER_DATE] [datetime2](7) NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
To specify that the "ID" column should start at value 1 and increment by 2, change it to IDENTITY(1,2).
EDIT*
ALTER TABLE [dbo].[RELATED]
ALTER COLUMN [Id] [int] IDENTITY(1,2) NOT NULL

Default Constraint causing an error

I have the following SQL to create a table, but the "DEFAULT" in the first CONSTRAINT is giving me an error: "A Default constraint can exist only at the column level in a CREATE or ALTER TABLE statement."
I've never used default before so I have done some looking into this with internet research, but nothing has helped me solve the error yet or even really explained it to me.
CREATE TABLE [RuleEngine].[NCCIImportHistory](
[NCCIImportHistoryID] [int] IDENTITY(1,1) NOT NULL,
[StartTime] [datetimeoffset](7) NOT NULL,
[EndTime] [datetimeoffset](7) NOT NULL,
[CreatedOn] [datetimeoffset](7) NOT NULL,
[CreatedBy_UserID] [int] NOT NULL,
CONSTRAINT [DF_NCCIImportHistory_CreatedOn] DEFAULT (getutcdate()) FOR [CreatedOn],
CONSTRAINT [FK_NCCIImportHistory_User_CreatedBy] FOREIGN KEY([CreatedBy_UserID]) REFERENCES [Security].[User] ([UserID]),
CONSTRAINT [PK_NCCIImportHistoryID] PRIMARY KEY CLUSTERED ([NCCIImportHistoryID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]) ON [PRIMARY]
You didn't specify what database you are using, but based on syntax I think it's MS SQL Server. If so you can add the constraint inline as part of the column definition instead, like this:
[CreatedOn] [datetimeoffset](7) NOT NULL CONSTRAINT [DF_NCCIImportHistory_CreatedOn] DEFAULT (getutcdate()),
Try this
CREATE TABLE [RuleEngine].[NCCIImportHistory]
(
[NCCIImportHistoryID] [INT] IDENTITY(1, 1)
NOT NULL ,
[StartTime] [DATETIMEOFFSET](7) NOT NULL ,
[EndTime] [DATETIMEOFFSET](7) NOT NULL ,
[CreatedOn] [DATETIMEOFFSET](7) NOT NULL CONSTRAINT [DF_NCCIImportHistory_CreatedOn] DEFAULT ( GETUTCDATE() ),
[CreatedBy_UserID] [INT] NOT NULL ,
CONSTRAINT [FK_NCCIImportHistory_User_CreatedBy] FOREIGN KEY ( [CreatedBy_UserID] ) REFERENCES [Security].[User] ( [UserID] ) ,
CONSTRAINT [PK_NCCIImportHistoryID] PRIMARY KEY CLUSTERED
( [NCCIImportHistoryID] ASC )
WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90 ) ON [PRIMARY]
)
ON [PRIMARY]
or first create table and then constraints like this
CREATE TABLE [RuleEngine].[NCCIImportHistory]
(
[NCCIImportHistoryID] [INT] IDENTITY(1, 1) NOT NULL ,
[StartTime] [DATETIMEOFFSET](7) NOT NULL ,
[EndTime] [DATETIMEOFFSET](7) NOT NULL ,
[CreatedOn] [DATETIMEOFFSET](7) NOT NULL,
[CreatedBy_UserID] [INT] NOT NULL
)
ON [PRIMARY]
GO
ALTER TABLE [RuleEngine].[NCCIImportHistory] ADD CONSTRAINT [DF_NCCIImportHistory_CreatedOn] DEFAULT( GETUTCDATE() ) FOR [CreatedOn]
GO
ALTER TABLE [RuleEngine].[NCCIImportHistory] ADD CONSTRAINT [FK_NCCIImportHistory_User_CreatedBy] FOREIGN KEY ( [CreatedBy_UserID] ) REFERENCES [Security].[User] ( [UserID] )
GO
ALTER TABLE [RuleEngine].[NCCIImportHistory] ADD CONSTRAINT [PK_NCCIImportHistoryID] PRIMARY KEY CLUSTERED( [NCCIImportHistoryID] ASC ) WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90 ) ON [PRIMARY]
GO

Problems understanding intermittent inconsistencies when loading data with SSIS package

The problem
During the passed few months the below described procedure has worked without any problems a vast majority of the times it has run (on 2008 r2). We have, however, three instances of incorrectly connected data. The question is, what is causing this and how do I remedy it?
DATA_PreImp
sourceid col01 col02 col03 col04 col...
100001 John Smith
100002 Calvin Klein
100003 Peter Parker
100004 Moe Greene
Usually the rendered result is that the attribute is connected to the Items_Main correctly but sometimes (less than 1%) the order is scrambled so that the value of col01 is not connected to the same Items_Main as the value of the rest of the columns.
Any insights as to what is causing this would be most appreciated.
The data moving procedure
We have an SSIS package that transfers data from a flat table called DATA_PreImp to a structure consisting of three related tables (attribute based).
Items_Main should contains one row for each row in DATA_PreImp
Items_Featurevalues contains one row for each column value of a row in DATA_PreImp
Items_MainRel contains the connection between Items_Main and Items_FeatureValues
The first step in the SSIS package inserts the data from DATA_PreImp to Items_Main and inserts the generated identifier into the TARGET_ID column in the empty DATA_PreImpMappingTMP table.
insert into items_main(creationdate, status)
output inserted.itemid into DATA_PreImpMappingTMP(TARGET_ID)
select getdate(), '0' from data_preimp
order by sourceid asc;
The second step in the SSIS package fill the Items_MainRel table with TARGET_ID (Itemid originally) and an identifier for the feature (in this case a 5).
insert into items_mainrel(itemid, featureid)
output inserted.itemrelid into DATA_PreImpMapping2TMP(INDREL_ID)
select TARGET_ID, 5 from DATA_PreImpMappingTMP
order by TARGET_ID asc;
The third step is to fill the SOURCE_ID column in the DATA_PreImpMapping2TMP table with the SOURCE_ID from DATA_PreImp.
with cte as (select sourceid, row_number() over (order by sourceid asc) as row from data_preimp)
update m set m.SOURCE_ID = s.sourceid, m.FEAT_ID = 5
from DATA_PreImpMapping2TMP as m
join cte as s on s.row = m.ROW;
The last step is to fill the Items_FeatureValues table with data from DATA_PreImpMapping2TMP and DATA_PreImp.
insert into items_featurevalues(itemrelid, languageid, fnvarchar)
select DATA_PreImpMapping2TMP.INDREL_ID, 0, data_preimp.col01
from DATA_PreImpMapping2TMP
join data_preimp on (DATA_PreImpMapping2TMP.SOURCE_ID = data_preimp.sourceid)
where FEAT_ID = 5
Data table structure
Here is what is needed to create the scenario:
CREATE TABLE [dbo].[DATA_PreImp](
[sourceid] [bigint] IDENTITY(1,1) NOT NULL,
[col01] [nvarchar](500) NULL,
[col02] [nvarchar](500) NULL,
[col03] [nvarchar](500) NULL,
[col04] [nvarchar](500) NULL,
[col05] [nvarchar](500) NULL,
[col06] [nvarchar](500) NULL,
[col07] [nvarchar](500) NULL,
[col08] [nvarchar](500) NULL,
[col09] [nvarchar](500) NULL,
[col10] [nvarchar](500) NULL,
CONSTRAINT [PK_DATA_PreImp] PRIMARY KEY CLUSTERED
(
[sourceid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[DATA_PreImpMappingTMP](
[ROW] [int] IDENTITY(1,1) NOT NULL,
[TARGET_ID] [int] NULL,
PRIMARY KEY CLUSTERED
(
[ROW] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[Items_Main](
[Itemid] [int] IDENTITY(1,1) NOT NULL,
[creationDate] [smalldatetime] NOT NULL,
[status] [int] NOT NULL,
[purchdate] [smalldatetime] NULL,
[logindate] [smalldatetime] NULL,
CONSTRAINT [PK_Items_Main] PRIMARY KEY CLUSTERED
(
[Itemid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[DATA_PreImpMapping2TMP](
[ROW] [int] IDENTITY(1,1) NOT NULL,
[SOURCE_ID] [int] NULL,
[INDREL_ID] [int] NULL,
[FEAT_ID] [int] NULL,
PRIMARY KEY CLUSTERED
(
[ROW] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[Items_Features](
[featureId] [int] IDENTITY(1,1) NOT NULL,
[featureRef] [varchar](15) NOT NULL,
[featureName] [varchar](50) NOT NULL,
[creationDate] [smalldatetime] NOT NULL,
[status] [int] NOT NULL,
[fieldType] [varchar](50) NOT NULL,
[featureType] [int] NOT NULL,
[featureDesc] [varchar](500) NULL,
CONSTRAINT [PK_Items_Features] PRIMARY KEY CLUSTERED
(
[featureId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]
CREATE TABLE [dbo].[Items_MainRel](
[ItemRelId] [int] IDENTITY(1,1) NOT NULL,
[Itemid] [int] NOT NULL,
[featureId] [int] NOT NULL,
CONSTRAINT [PK_Items_MainRel] PRIMARY KEY CLUSTERED
(
[ItemRelId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Items_FeatureValues](
[valueId] [int] IDENTITY(1,1) NOT NULL,
[ItemRelId] [int] NOT NULL,
[languageId] [int] NOT NULL,
[FnVarChar] [nvarchar](250) NULL,
[FInt] [int] NULL,
[FImage] [int] NULL,
[FNText] [ntext] NULL,
[FSmallDateTime] [smalldatetime] NULL,
CONSTRAINT [PK_Items_FeatureValues] PRIMARY KEY CLUSTERED
(
[valueId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Items_MainRel] WITH CHECK ADD CONSTRAINT [FK_Items_MainRel_Items_Features] FOREIGN KEY([featureId])
REFERENCES [dbo].[Items_Features] ([featureId])
GO
ALTER TABLE [dbo].[Items_MainRel] CHECK CONSTRAINT [FK_Items_MainRel_Items_Features]
GO
ALTER TABLE [dbo].[Items_MainRel] WITH CHECK ADD CONSTRAINT [FK_Items_MainRel_Items_Main] FOREIGN KEY([Itemid])
REFERENCES [dbo].[Items_Main] ([Itemid])
GO
ALTER TABLE [dbo].[Items_MainRel] CHECK CONSTRAINT [FK_Items_MainRel_Items_Main]
GO
ALTER TABLE [dbo].[Items_FeatureValues] WITH CHECK ADD CONSTRAINT [FK_Items_FeatureValues_Items_MainRel] FOREIGN KEY([ItemRelId])
REFERENCES [dbo].[Items_MainRel] ([ItemRelId])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Items_FeatureValues] CHECK CONSTRAINT [FK_Items_FeatureValues_Items_MainRel]
GO
INSERT INTO DATA_PreImp (col01,col02,col03,col04)
VALUES('John', 'Smith', '1964', 'NewYork'),
('Calvin', 'Klein', '1960', 'Washington D. C.'),
('Peter', 'Parker', '1974', 'Losangles'),
('Moe', 'Greene', '1928', 'Lasvegas')
INSERT INTO Items_Features (featureRef, featureName, creationDate, [status], fieldType, featureType, featureDesc)
VALUES ('firstname','First_Name', GETDATE(), 0, 'FnVarChar', 3, 'FirstName'),
('lastname','Last_Name', GETDATE(), 0, 'FnVarChar', 3, 'LastName'),
('Birth','Birth', GETDATE(), 0, 'FnVarChar', 3, 'Birth'),
('City','City', GETDATE(), 0, 'FnVarChar', 3, 'City')
The problem was the computed column CUST_CD. After a lot of researching, it seems that the BULK INSERT does not like complex computed types (see Using SQL Server spatial types in SSIS data load). The solution is to removed the computed column and just make it a varchar(20) NULL. Then I created a new Execute SQL Task that updates any NULL rows with the computed value.

How should I migrate this data into these Sql Server tables?

I wish to migrate some data from a single table into these new THREE tables.
Here's my destination schema:
Notice that I need to insert into the first Location table .. grab the SCOPE_IDENTITY() .. then insert the rows into the Boundary and Country tables.
The SCOPE_IDENTITY() is killing me :( meaning, I can only see a way to do this via CURSORS. Is there a better alternative?
UPDATE
Here's the scripts for the DB Schema....
Location
CREATE TABLE [dbo].[Locations](
[LocationId] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[OriginalLocationId] [int] NOT NULL,
CONSTRAINT [PK_Locations] PRIMARY KEY CLUSTERED
(
[LocationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
)
Country
CREATE TABLE [dbo].[Locations_Country](
[IsoCode] [nchar](2) NOT NULL,
[LocationId] [int] NOT NULL,
CONSTRAINT [PK_Locations_Country] PRIMARY KEY CLUSTERED
(
[LocationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Locations_Country] WITH CHECK ADD CONSTRAINT [FK_Country_inherits_Location] FOREIGN KEY([LocationId])
REFERENCES [dbo].[Locations] ([LocationId])
GO
ALTER TABLE [dbo].[Locations_Country] CHECK CONSTRAINT [FK_Country_inherits_Location]
GO
Boundary
CREATE TABLE [dbo].[Boundaries](
[LocationId] [int] NOT NULL,
[CentrePoint] [varbinary](max) NOT NULL,
[OriginalBoundary] [varbinary](max) NULL,
[LargeReducedBoundary] [varbinary](max) NULL,
[MediumReducedBoundary] [varbinary](max) NULL,
[SmallReducedBoundary] [varbinary](max) NULL,
CONSTRAINT [PK_Boundaries] PRIMARY KEY CLUSTERED
(
[LocationId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Boundaries] WITH CHECK ADD CONSTRAINT [FK_LocationBoundary] FOREIGN KEY([LocationId])
REFERENCES [dbo].[Locations] ([LocationId])
GO
ALTER TABLE [dbo].[Boundaries] CHECK CONSTRAINT [FK_LocationBoundary]
GO
I don't see a need for SCOPE_IDENTITY or cursors if you approach the data in order of the parent/child relationship:
INSERT INTO LOCATION
SELECT t.name,
t.originallocationid
FROM ORIGINAL_TABLE t
GROUP BY t.name, t.originallocationid
INSERT INTO COUNTRY
SELECT DISTINCT
t.isocode,
l.locationid
FROM ORIGINAL_TABLE t
JOIN LOCATION l ON l.name = t.name
AND l.originallocationid = t.originalocationid
INSERT INTO BOUNDARY
SELECT DISTINCT
l.locationid,
t.centrepoint,
t.originalboundary,
t.largereducedboundary,
t.mediumreducedboundary,
t.smallreducedboundary
FROM ORIGINAL_TABLE t
JOIN LOCATION l ON l.name = t.name
AND l.originallocationid = t.originalocationid
After loading your Location table you could create a query that joins Location with your source single table. The join criteria would be the natural key (is that the Name column?) and it would return the new LocationId along with the Boundary data. The results would inserted into the new Boundary table.