我有两个数据表:GroupTable和PeopleTable。
GroupTable有以下列:id,continent,country
PeopleTable有以下列:id,groupId,name
groupId是GroupTable.id的外键
这两个表已经从我的应用程序中填充。我想要做的是创建一个存储过程,将两个表的内容复制到相同的表,但更改GroupTable的continent
列。因此,PeopleTable中的新行将指向GroupTable中的新行。存储过程的输入是@sourceCont,@ destinationCont
我有什么:
GroupTable:
id | continent | company
0 | europe | aa
1 | europe | bb
2 | europe | cc
PeopleTable:
id | groupId | name
0 | 0 | John
1 | 0 | Mary
2 | 0 | Nick
3 | 1 | Peter
4 | 2 | Michel
这就是我想要的(@sourceCont = europe,@ destinationCont = america)
GroupTable:
id | continent | company
0 | europe | aa
1 | europe | bb
2 | europe | cc
3 | america | aa
4 | america | bb
5 | america | cc
PeopleTable:
id | groupId | name
0 | 0 | John
1 | 0 | Mary
2 | 0 | Nick
3 | 1 | Peter
4 | 2 | Michel
5 | 3 | John
6 | 3 | Mary
7 | 3 | Nick
8 | 4 | Peter
9 | 5 | Michel
答案 0 :(得分:1)
CREATE Proc Rocount
@sourceCont NVARCHAR(50), @destinationCont NVARCHAR(50)
AS
BEGIN
SET NOCOUNT ON
DECLARE @String_sql NVARCHAR(MAX),@Maxid INT
--NOTE IF GroupID Is AUto Generated IN GroupTable
SET @String_sql='Insert INTO GroupTable
SELECT '''+@destinationCont+''' FROM GroupTable WHERE continent ='''+@sourceCont+''' '
PRINT @String_sql
EXEC (@String_sql)
SELECT @Maxid= ID FROM GroupTable WHERE continent = @destinationCont
SET @String_sql='Insert INTO PeopleTable
SELECT ID,'''+CONVERT(NVARCHAR(2),@Maxid)+''',name
FROM PeopleTable WHERE GroupID IN (SELECT GroupID FROM GroupTable WHERE continent ='''+@sourceCont+''')'
PRINT @String_sql
EXEC (@String_sql)
END