添加行并填充另一个表(pivot)

时间:2013-05-02 00:02:28

标签: sql sql-server tsql sql-server-2012

两个问题: SQL SERVER 2012 我有一张桌子A (P_ID IDENTITY INT, P_Name CHAR(2), Cust_ID INT)

P_ID      P_Name   Cust_ID
547       08        1
147       2B        1
21        K4        2

我想通过在#Temp Table中创建自动生成的新P_ID和新P_Name来复制行。插入新行会自动生成P_ID。

SELECT * INTO #Temp FROM TableA
INSERT INTO #Temp (P_Name, Cust_ID)
SELECT  SUBSTRING(REPLACE(CONVERT(VARCHAR(36), NEWID()) , '-', ''), 0, 3), Cust_ID FROM TableA

但我想确保新的P_Name是唯一的。如何仅填充唯一的P_Names

我也有

TableB (P_ID, P_Name, Cust_ID, New_P_ID, New_P_Name)

如何使用临时表中的所有记录和new_P_ID以及new_P_Name值填充TableB

1 个答案:

答案 0 :(得分:1)

除非您想创建一个函数,否则我认为您需要使用基于游标的解决方案。

我首先创建TableB,然后根据需要将值从TableB复制到临时表。这个,或者您需要将TableA中的主键添加到临时表中,以便在以后在TableB中插入行时正确映射它。

以下代码可用于插入TableB,您需要为New_P_ID添加逻辑:

DECLARE cur CURSOR FOR SELECT P_ID, P_Name, cust_id FROM TableA
DECLARE @id int
DECLARE @name nchar(2)
DECLARE @cust_id int

OPEN cur

FETCH NEXT FROM cur INTO @id, @name, @cust_id

WHILE (@@FETCH_STATUS = 0)
BEGIN
    Select @id, @name, @cust_id

    -- Get a unique name, this will hang if all 
    -- names are taken...
    DECLARE @newName nchar(2)
    DECLARE @notUnique bit = 1
    WHILE (@notUnique = 1)
    BEGIN
        SET @newName = SUBSTRING(REPLACE(CONVERT(VARCHAR(36), NEWID()) , '-', ''), 0, 3)
        SELECT @notUnique = COUNT(*) FROM TableB where New_P_Name = @newName
    END

    -- TODO: Generate the New_P_ID here...
    DECLARE @new_p_id int = 42;

    INSERT INTO TableB(P_ID, P_Name, cust_id, New_P_ID, New_P_Name)
    VALUES (@id, @name, @cust_id, @new_p_id, @newName)

    FETCH NEXT FROM cur INTO @id, @name, @cust_id
END

CLOSE cur
DEALLOCATE cur