SQL Server数据库复制数据并更新一列

时间:2018-02-26 14:46:23

标签: sql sql-server database copy

我有一个现有的表[dba.Text],表中的所有数据都必须保留在那里,我唯一想要的是复制2017年的所有数据并将其更改为2018.我试图制作它在Excel中显示我的意思:

How the table should look like

希望有人能引导我朝着正确的方向前进。

3 个答案:

答案 0 :(得分:1)

如果我做对了,我认为你需要这样的东西(我假设PageId是自动递增的)

INSERT INTO <your_table>
SELECT
    Key
    ,Value
    ,2018
FROM <your_table>
WHERE Year = 2017

答案 1 :(得分:0)

考虑我们有如下表格

    CREATE TABLE [dbo].[Test](
        [year] [int] NULL,
        [MedTitle] [varchar](50) NULL,
        [FullTitle] [varchar](50) NULL
    ) ON [PRIMARY]

    GO

---insert values for the table 
INSERT INTO [dbo].[Test]
           ([year]
           ,[MedTitle]
           ,[FullTitle])
     VALUES
           (<year, int,>
           ,<MedTitle, varchar(50),>
           ,<FullTitle, varchar(50),>)
GO

表格内容:

    year    MedTitle    FullTitle
    2017    1   This is first
    2017    2   This is first
    2017    3   This is first

然后:

    Declare @year  int,
    @MedTitle varchar(50),
    @FullTitle varchar(50)

    Declare AIX Cursor
           for Select year, MedTitle, FullTitle
            from [dbo].[Test] where year=2017
    Open AIX;
        Fetch Next from AIX into @year,@MedTitle,@FullTitle;
    WHILE @@FETCH_STATUS = 0
    BEGIN
    --set @aixrowid = (select MAX(aixrowid)+1 from [dbo].[Test])

    insert [dbo].[test] (year, MedTitle, FullTitle)
        values  (2018,@MedTitle,@FullTitle)
    FETCH NEXT FROM AIX 
        INTO  @year, @MedTitle,@FullTitle;
    END
    CLOSE AIX;
    DEALLOCATE AIX;

最后

    Select * from dbo.text

结果:

    year    MedTitle    FullTitle
    2017    1   This is first
    2017    2   This is first
    2017    3   This is first
    2018    1   This is first
    2018    2   This is first
    2018    3   This is first

答案 2 :(得分:0)

感谢帮助家伙,我想出了如何更新这一年。我尝试了以下声明

INSERT INTO [dbo].[TEST]
       ([PageID]
       ,[Key]
       ,[Value]
       ,[Year])

       (SELECT [PageID]
  ,[Key]
  ,[Value], '2018' 
FROM [database name].[dbo].[TEST] 
where Year = '2017'
)