zoukankan      html  css  js  c++  java
  • 使用merge-using语句初始化数据库

    创建三张表Student、Course、Enrollment

    CREATE TABLE [dbo].[Student] (
        [StudentID]      INT           IDENTITY (1, 1) NOT NULL,
        [LastName]       NVARCHAR (50) NULL,
        [FirstName]      NVARCHAR (50) NULL,
        [EnrollmentDate] DATETIME      NULL,
        PRIMARY KEY CLUSTERED ([StudentID] ASC)
    )
    CREATE TABLE [dbo].[Course] (
        [CourseID] INT           IDENTITY (1, 1) NOT NULL,
        [Title]    NVARCHAR (50) NULL,
        [Credits]  INT           NULL,
        PRIMARY KEY CLUSTERED ([CourseID] ASC)
    )
    CREATE TABLE [dbo].[Enrollment] (
        [EnrollmentID] INT IDENTITY (1, 1) NOT NULL,
        [Grade]        DECIMAL(3, 2) NULL,
        [CourseID]     INT NOT NULL,
        [StudentID]    INT NOT NULL,
        PRIMARY KEY CLUSTERED ([EnrollmentID] ASC),
        CONSTRAINT [FK_dbo.Enrollment_dbo.Course_CourseID] FOREIGN KEY ([CourseID]) 
            REFERENCES [dbo].[Course] ([CourseID]) ON DELETE CASCADE,
        CONSTRAINT [FK_dbo.Enrollment_dbo.Student_StudentID] FOREIGN KEY ([StudentID]) 
            REFERENCES [dbo].[Student] ([StudentID]) ON DELETE CASCADE
    )

    不会覆盖或删除数据库已经存在的数据,将数据作为一张表更新到另一张表中。

    merge into Course as Target
    using (values
           (1,'Economics',3),
           (2,'Literrature',3),
           (3,'Chemistry',4)

    )
    as Source (CourseID,Title,Credits)
    on Target.CourseID =Source.CourseID
    when not matched by target then
    Insert(Title,Credits)
    values(Title,Credits);

    merge into Student as Target
    using(values
         (1,'Tibbetts','Donnie','2013-09-01'),
      (2,'Guzman','Liza','2012-01-13'),
      (3,'Catlett','Phil','2011-09-03')
    )
    as Source (StudentID,LastName,FirstName,EnrollmentDate)
    on Target.StudentID=Source.StudentID
    when not matched by Target then
    Insert (LastName,FirstName,EnrollmentDate)
    values (LastName,FirstName,EnrollmetnDate);

    Merge into Enrollment as Target
    using (values
           (1,2.00,1,1),
        (2,3.50,2,2),
        (3,4.00,2,3),
        (4,1.80,2,1),
        (5,3.20,3,1),
        (6,4.00,3,2)
    )
    as Source (EnrollmentID,Grade,CourseID,StudentID)
    on Target.EnrollmentID =Source.EnrollmentID
    when not matched by Target then
    Insert (Grade,CourseID,StudentID)
    values (Grade,CourseID,StudentID);

  • 相关阅读:
    Python-cookie,session
    Django_models下划线__正反查询,对象正反查询
    Python利用PIL生成随机验证码图片
    简单实用的分页类-python
    Django_Form验证(三)字段,字段的参数,widgets种类
    Django_Form验证(二),ajax验证
    Django_Form验证(一)
    Django提交文件的方式
    在linux下安装python3.6.6
    celery学习
  • 原文地址:https://www.cnblogs.com/liuyuanhao/p/4285640.html
Copyright © 2011-2022 走看看