Sql many to many relation with the same table - sql

I want to create a table of users, lets name it USERS and I want that each
user will be able to point to more users. You can think of it as a user that have some friends who are also user, and have more friends that are also user and so on.
Do I need to use many to many relation between this table to itself or use a junction table?
For instance the table (without the notation of junction table) might look like:
| USER_ID(PK) | NAME | AGE | _ID(FK) |

You should use a junction table where each row contains details of a "relationship" between two users.
|UserID1|UserID2|
| 1| 2|
| 2| 3|

You need another table n:n where usersID's are saved, for example there would be for each friend of yours an record including yourId and onefriendsId

As you already mentioned, you have one object named 'User' and the other named 'Person'. These two have a Factory relation which means "Every 'Person' definitely is a 'User'" but "Every 'User' might not be a 'Person'", also means that "Every 'User' that is also 'Person' can have related 'Person's by using 'PersonOrder' as a junction table" and the other constraint is that as a junction table "Each child 'Person' must be unique".
I know that it's so far as you really need to implement, but it is a normalized structure. If I were you, I'd implement this way.
Link to Diagram: http://sdrv.ms/ROVtJc
Cheers
USE [temp]
GO
/****** Object: Table [dbo].[User] Script Date: 09/06/2012 17:11:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[User](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[Age] [tinyint] NOT NULL,
CONSTRAINT [PK_User] 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
/****** Object: Table [dbo].[Person] Script Date: 09/06/2012 17:11:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Person](
[Id] [bigint] NOT NULL,
CONSTRAINT [PK_Person] 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
/****** Object: Table [dbo].[PersonOrder] Script Date: 09/06/2012 17:11:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PersonOrder](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Person_Parent_Id] [bigint] NOT NULL,
[Person_Child_Id] [bigint] NOT NULL,
CONSTRAINT [PK_PersonOrder] 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],
CONSTRAINT [IX_FriendOrder_Child_Unique] UNIQUE NONCLUSTERED
(
[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
/****** Object: ForeignKey [FK_Person_User] Script Date: 09/06/2012 17:11:23 ******/
ALTER TABLE [dbo].[Person] WITH CHECK ADD CONSTRAINT [FK_Person_User] FOREIGN KEY([Id])
REFERENCES [dbo].[User] ([Id])
GO
ALTER TABLE [dbo].[Person] CHECK CONSTRAINT [FK_Person_User]
GO
/****** Object: ForeignKey [FK_PersonOrder_Person_Child] Script Date: 09/06/2012 17:11:23 ******/
ALTER TABLE [dbo].[PersonOrder] WITH CHECK ADD CONSTRAINT [FK_PersonOrder_Person_Child] FOREIGN KEY([Person_Parent_Id])
REFERENCES [dbo].[Person] ([Id])
GO
ALTER TABLE [dbo].[PersonOrder] CHECK CONSTRAINT [FK_PersonOrder_Person_Child]
GO
/****** Object: ForeignKey [FK_PersonOrder_Person_Parent] Script Date: 09/06/2012 17:11:23 ******/
ALTER TABLE [dbo].[PersonOrder] WITH CHECK ADD CONSTRAINT [FK_PersonOrder_Person_Parent] FOREIGN KEY([Person_Child_Id])
REFERENCES [dbo].[Person] ([Id])
GO
ALTER TABLE [dbo].[PersonOrder] CHECK CONSTRAINT [FK_PersonOrder_Person_Parent]
GO

Related

How can a join table be part of an ON DELETE CASCADE cycle?

In SQL Server I have a simple database schema, where Authors and Books have a many-many join table, and both have foreign keys to Publishers.
I am not allowed to set ON CASCADE DELETE on all the relations:
Unable to create relationship 'FK_Books_Publishers'.
Introducing FOREIGN KEY constraint 'FK_Books_Publishers' on table 'Books' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
What's the cycle here? Don't cascade cycles end at join tables as they have no foreign keys referencing them?
Or is it that deleting a Publisher may give two causes for deleting a BookAuthor row (via Authors or via Books)? And why would that be a problem?
This is the DDL for the above:
USE [fk-test]
GO
/****** Object: Table [dbo].[Authors] Script Date: 3-6-2022 15:23:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Authors](
[Id] [int] NOT NULL,
[PublisherId] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_Authors] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[BookAuthor] Script Date: 3-6-2022 15:23:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[BookAuthor](
[BookId] [int] NOT NULL,
[AuthorId] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Books] Script Date: 3-6-2022 15:23:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Books](
[Id] [int] NOT NULL,
[PublisherId] [int] NOT NULL,
[Title] [nchar](50) NULL,
CONSTRAINT [PK_Books] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Publishers] Script Date: 3-6-2022 15:23:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Publishers](
[Id] [int] NOT NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_Publishers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Authors] WITH CHECK ADD CONSTRAINT [FK_Authors_Authors] FOREIGN KEY([PublisherId])
REFERENCES [dbo].[Publishers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Authors] CHECK CONSTRAINT [FK_Authors_Authors]
GO
ALTER TABLE [dbo].[BookAuthor] WITH CHECK ADD CONSTRAINT [FK_BookAuthor_Authors] FOREIGN KEY([AuthorId])
REFERENCES [dbo].[Authors] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[BookAuthor] CHECK CONSTRAINT [FK_BookAuthor_Authors]
GO
ALTER TABLE [dbo].[BookAuthor] WITH CHECK ADD CONSTRAINT [FK_BookAuthor_Books] FOREIGN KEY([BookId])
REFERENCES [dbo].[Books] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[BookAuthor] CHECK CONSTRAINT [FK_BookAuthor_Books]
GO
ALTER TABLE [dbo].[Books] WITH CHECK ADD CONSTRAINT [FK_Books_Publishers] FOREIGN KEY([PublisherId])
REFERENCES [dbo].[Publishers] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Books] CHECK CONSTRAINT [FK_Books_Publishers]
GO
It's because there'd be two cascading delete paths from Publisher to BookAuthor,one via Author and one via Books.
A solutions is to modify the two foreign keys
FK_Authors_Authors
FK_Books_Publishers
to
ON DELETE SET NULL
And make PublisherId in Books and Authors nullable.
Then you'll need to do your own custom cascade delete code when deleting a publisher. e.g delete the publisher, then delete the relevant Authors and Books.

The specified schema name either does not exist or you do not have permission to use it

I am trying to create replica of my database from SQL server to another.
For that I am generating script from original server and trying to run in another server. I've created database manually with the same name.
Here is the screenshot of original database
When I generate script, following script is created which I am trying in another server
USE [ContactsApp]
GO
/****** Object: Table [common].[BU] Script Date: 2/12/2016 3:02:29 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [common].[BU](
[ID] [int] IDENTITY(1,1) NOT NULL,
[IndustryID] [int] NOT NULL,
[BU] [varchar](50) NOT NULL,
[Code] [varchar](2) NOT NULL,
[Active] [bit] NOT NULL,
[CreatedBy] [uniqueidentifier] NOT NULL,
[CreateDate] [date] NOT NULL,
[CreateTime] [time](3) NOT NULL,
[ModifiedBy] [uniqueidentifier] NULL,
[ModifyDate] [date] NULL,
[ModifyTime] [time](3) NULL,
CONSTRAINT [PK_BU] 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],
CONSTRAINT [UK_BU_Code] UNIQUE NONCLUSTERED
(
[Code] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [UK_BU_Name] UNIQUE NONCLUSTERED
(
[BU] 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 [common].[BU] ADD CONSTRAINT [DF_BU_CreateDate] DEFAULT (CONVERT([date],getdate())) FOR [CreateDate]
GO
ALTER TABLE [common].[BU] ADD CONSTRAINT [DF_BU_CreateTime] DEFAULT (CONVERT([time],getdate())) FOR [CreateTime]
GO
ALTER TABLE [common].[BU] WITH CHECK ADD CONSTRAINT [FK_BU_Industry] FOREIGN KEY([IndustryID])
REFERENCES [common].[Industry] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [common].[BU] CHECK CONSTRAINT [FK_BU_Industry]
GO
When I try to run this script, I get following error
The specified schema name "common" either does not exist or you do
not have permission to use it.
I don't know what is the meaning of common here.Thanks
Your tables are 'grouped' (for want of better word) in schemas (google for it). You should run
CREATE SCHEMA common
And likewise for all other schemas.

UNIQUE Constraint For Columns On Different Tables

I have three tables a,b,and c each with an int IDENTITY PK field that relates to the child table.
CREATE TABLE [dbo].[a]([aID] [int] IDENTITY(1,1) NOT NULL,[aCode] [varchar](20) NOT NULL,
CONSTRAINT [PK_a] PRIMARY KEY CLUSTERED([aID] 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].[b]([bID] [int] IDENTITY(1,1) NOT NULL,[aID] [int] NOT NULL, [bCode] [varchar](20) NOT NULL,
CONSTRAINT [PK_b] PRIMARY KEY CLUSTERED([bID] 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].[c]([cID] [int] IDENTITY(1,1) NOT NULL,[bID] [int] NOT NULL,[cCode] [varchar](20) NOT NULL,
CONSTRAINT [PK_c] PRIMARY KEY CLUSTERED([cID] 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].[b] WITH CHECK ADD CONSTRAINT [FK_b_a] FOREIGN KEY([aID])
REFERENCES [dbo].[a] ([aID])
GO
ALTER TABLE [dbo].[b] CHECK CONSTRAINT [FK_b_a]
GO
ALTER TABLE [dbo].[c] WITH CHECK ADD CONSTRAINT [FK_c_b] FOREIGN KEY([bID])
REFERENCES [dbo].[b] ([bID])
GO
ALTER TABLE [dbo].[c] CHECK CONSTRAINT [FK_c_b]
GO
How do I create a CONSTRAINT that enforces a unique condition for a.aID, c.cCode?
If you are looking for a unique constraint over a combination of columns a.aID, c.cCode one way is to alter table c and add [aid] column to it and have a composite unique key.
ALTER TABLE [dbo].[c](
[cID] [int] IDENTITY(1,1) NOT NULL,
[bID] [int] NOT NULL,[cCode] [varchar](20) NOT NULL,
[cCode] [varchar](20) NOT NULL,
[aID] INT FOREIGN KEY REFERENCES [a]([aID]) NOT NULL,
CONSTRAINT uq_cCode_aid UNIQUE NONCLUSTERED (cCode,aID),
CONSTRAINT [PK_c] PRIMARY KEY CLUSTERED([cID] 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
You can add a unique constraint as follows:
ALTER TABLE [C] ADD CONSTRAINT [uc_C_cCode] UNIQUE NONCLUSTERED [cCode];
You cannot however enforce a constraint across tables, which is what it sounds like you are trying to do.
As for table A.aID, its a primary key, it will already have a unique constraint.
I found a way to get what I wanted (I think) using an indexed view. Please comment on if this seems appropriate. My tests so far conclude that it does work.
I created a view with schemabinding on joining c to a (going through b).
I created an clustered index to enforce unique on aID and cCode.
This allows me to not need to include aID within the c table but still enforces the unique constraint.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[vw.aIDcCode] WITH SCHEMABINDING
AS
SELECT dbo.a.aID, dbo.c.cCode
FROM dbo.a
INNER JOIN
dbo.b ON dbo.a.aID = dbo.b.aID
INNER JOIN
dbo.c ON dbo.b.bID = dbo.c.bID
GO
SET ARITHABORT ON
GO
SET CONCAT_NULL_YIELDS_NULL ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
SET ANSI_PADDING ON
GO
SET ANSI_WARNINGS ON
GO
SET NUMERIC_ROUNDABORT OFF
GO
CREATE UNIQUE CLUSTERED INDEX [IDX_Unique_aIDcCode] ON [dbo].[vw.aIDcCode]
([aID] ASC, [cCode] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
ON [PRIMARY]
GO

use two primary keys attribute from a table with different title

I got table "Functions" with Function_ID {PK} and I want another table "Hierarchy" with Hierarchy_ID {PK} which defines tree structure of functions so i need one Function_ID from Function table AS Parent_ID and one Function_ID AS Child. my question is how i can use two primary keys from another table to make it together as Foreign key
I am using SQL Server 2012 and the Management Studio
Many Thanks
Actually you just need to add a ParentFunction_ID column in the Functions table.
You don't need another table if your structure is indeed a tree.
Then make the ParentFunction_ID to be a FK to the same table Functions.
So ParentFunction_ID (FK) would be pointing to Function_ID (PK).
The only record which has ParentFunction_ID NULL would be the root of your tree.
Here is some sample code:
USE [test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Functions](
[Function_ID] [int] IDENTITY(1,1) NOT NULL,
[FunctionCode] [varchar](max) NULL,
[ParentFunction_ID] [int] NULL,
CONSTRAINT [PK_Functions] PRIMARY KEY CLUSTERED
(
[Function_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
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Functions] WITH CHECK ADD CONSTRAINT [FK_Functions_Functions] FOREIGN KEY([ParentFunction_ID])
REFERENCES [dbo].[Functions] ([Function_ID])
GO
ALTER TABLE [dbo].[Functions] CHECK CONSTRAINT [FK_Functions_Functions]
GO
Name your Functions table a Function table. AFAIK using
plurals for table names is not really a good practice.
So you can do this.
--- 1 ---
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Function](
[Function_ID] [int] IDENTITY(1,1) NOT NULL,
[FunctionCode] [varchar](max) NULL,
CONSTRAINT [PK_Function] PRIMARY KEY CLUSTERED
(
[Function_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
SET ANSI_PADDING OFF
GO
--- 2 ---
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Hierarchy](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ParentFunction_ID] [int] NULL,
[ChildFunction_ID] [int] NULL,
CONSTRAINT [PK_Hierarchy] 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].[Hierarchy] WITH CHECK ADD CONSTRAINT [FK_Hierarchy_Function] FOREIGN KEY([ParentFunction_ID])
REFERENCES [dbo].[Function] ([Function_ID])
GO
ALTER TABLE [dbo].[Hierarchy] CHECK CONSTRAINT [FK_Hierarchy_Function]
GO
ALTER TABLE [dbo].[Hierarchy] WITH CHECK ADD CONSTRAINT [FK_Hierarchy_Function1] FOREIGN KEY([ChildFunction_ID])
REFERENCES [dbo].[Function] ([Function_ID])
GO
ALTER TABLE [dbo].[Hierarchy] CHECK CONSTRAINT [FK_Hierarchy_Function1]
GO

SQL Server : complicated inserts

I have two tables, which I want to fill with data. Those tables are Threads and Posts. Also I have a table called Source which contains data.
Threads and Posts contain a lot of columns to be filled, so I will not paste them here for the sake of simplicity, but most of them can be some fixed value. Source table contains following columns - title (goes into Threads.title), postContent (goes into Posts.content)
In order to copy data:
I need to copy title column from Source table into Threads table, and add some fixed date, and author username into it (I want author to be some constant string, and date to be autogenerated DateTime from some T-SQL function)
Now when the Threads row is created, I need to get it's ID, and create new Posts row, which will contain ID of new thread, content from Source.postContent, and some other fixed values
I know that this probably is complicated, but can you maybe give me some guidelines here? How do I do such a thing? The main issue here, is the need of creating Threads first, and then using it's ID in Posts.
Please try with the below code snippet.
Create Table and add dummy data
/****** Object: Table [dbo].[Threads] Script Date: 11/06/2013 13:57:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Threads](
[ThreadID] [int] IDENTITY(1,1) NOT NULL,
[ThreadTitle] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Threads] PRIMARY KEY CLUSTERED
(
[ThreadID] 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
/****** Object: Table [dbo].[SourceTable] Script Date: 11/06/2013 13:57:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SourceTable](
[SourceTableID] [int] IDENTITY(1,1) NOT NULL,
[SourceTitle] [nvarchar](50) NULL,
[SourceContent] [nvarchar](50) NULL,
CONSTRAINT [PK_SourceTable] PRIMARY KEY CLUSTERED
(
[SourceTableID] 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
/****** Object: Table [dbo].[Posts] Script Date: 11/06/2013 13:57:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Posts](
[PostID] [int] IDENTITY(1,1) NOT NULL,
[PostContent] [nvarchar](50) NULL,
[ThreadID] [int] NOT NULL,
CONSTRAINT [PK_Posts] PRIMARY KEY CLUSTERED
(
[PostID] 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
/****** Object: ForeignKey [FK_Posts_Threads] Script Date: 11/06/2013 13:57:51 ******/
ALTER TABLE [dbo].[Posts] WITH CHECK ADD CONSTRAINT [FK_Posts_Threads] FOREIGN KEY([ThreadID])
REFERENCES [dbo].[Threads] ([ThreadID])
GO
ALTER TABLE [dbo].[Posts] CHECK CONSTRAINT [FK_Posts_Threads]
GO
SET IDENTITY_INSERT [dbo].[SourceTable] ON
INSERT [dbo].[SourceTable] ([SourceTableID], [SourceTitle], [SourceContent]) VALUES (1, N'blog1', N'blogdesc1')
INSERT [dbo].[SourceTable] ([SourceTableID], [SourceTitle], [SourceContent]) VALUES (2, N'blog2', N'blogdesc2')
INSERT [dbo].[SourceTable] ([SourceTableID], [SourceTitle], [SourceContent]) VALUES (3, N'blog3', N'blogdesc3')
SET IDENTITY_INSERT [dbo].[SourceTable] OFF
Query to insert data in table
CREATE TABLE #SummaryOfChanges(actionType NVARCHAR(50),ThreadID NVARCHAR(40),SourceContent NVARCHAR(40))
MERGE INTO Threads AS d
USING (SELECT SourceTableID,SourceTitle,SourceContent FROM SourceTable) AS s
ON 1 = 2
WHEN NOT MATCHED THEN
INSERT (ThreadTitle)
VALUES (s.SourceTitle)
OUTPUT $action, Inserted.ThreadID, s.SourceContent INTO #SummaryOfChanges;
MERGE INTO Posts AS d
USING (SELECT ThreadID,SourceContent FROM #SummaryOfChanges) AS s
ON d.ThreadID = s.ThreadID
WHEN MATCHED THEN
UPDATE SET d.PostContent= s.SourceContent
WHEN NOT MATCHED THEN
INSERT (ThreadID,PostContent)
VALUES (ThreadID,s.SourceContent);
DROP TABLE #SummaryOfChanges
Let me know if any concern.