复制条目并分配给另一个用户

时间:2019-02-26 10:47:18

标签: sql sql-server

我有一个问题:我想复制表PlanData where userID='38'中的所有数据,然后将复制数据的userID更改为userID='39'。因此,UserID是表中许多列的其中之一。

我该怎么做?

谢谢

2 个答案:

答案 0 :(得分:3)

尝试以下-

insert into PlanData(userid, col2,col3)
   select 39 as userid,col2,col3 from PlanData where userID='38'

答案 1 :(得分:0)

如果您不想对列名进行硬编码,则可以使用临时表作为第一步。

出于测试原因,下面的示例代码段也将临时表用于PlanData。

-- Test table
IF OBJECT_ID('tempdb..#PlanData') IS NOT NULL DROP TABLE #PlanData;
CREATE TABLE #PlanData (ID INT PRIMARY KEY IDENTITY(1,1), userID INT, Col1 VARCHAR(30));

-- Sample Data
insert into #PlanData (userID, Col1) values
(36,'A'),(36,'B'),(36,'C'),
(38,'X'),(38,'Y'),(38,'Z');

-- Create a temporary table with data from the original user
IF OBJECT_ID('tempdb..#tmpPlanData') IS NOT NULL DROP TABLE #tmpPlanData;
SELECT * INTO #tmpPlanData FROM #PlanData WHERE 0=1
UNION ALL 
SELECT * FROM #PlanData WHERE userID = 38;

-- Remove the identity column from the temp table
-- This assumes that the ID column is the first column in the table
ALTER TABLE #tmpPlanData DROP COLUMN ID;

-- Set the userId to the new userId in the temporary table
UPDATE #tmpPlanData SET userID = 39;

-- Insert all from the temporary table into the destination table
INSERT INTO #PlanData 
SELECT * FROM #tmpPlanData;

-- Check the inserts
SELECT * FROM #PlanData
WHERE userID = 39;
相关问题