如何在sql server中编写动态插入语句?

时间:2016-01-21 10:55:32

标签: sql sql-server sql-server-2008

我有一张Student表和Department表。  学生表包含三列

StudentId  |  DeptId  | StudentName

部门表包含

DeptId  |  DeptName

可能是DeptTable有时不存在的情况。那就是我正在部署带有两个场景的脚本,有时是部门,有时没有。在没有部门的情况下,departmentId将不在学生表中 因此,当部门表存在时,我必须插入DeptId的值,否则我必须编写没有departmentId的插入语句

IF (EXISTS(
        SELECT 1
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE table_name = 'Department'
            AND column_name = 'DeptId'
    ))
DECLARE @DeptId UNIQUEIDENTIFIER;
SET @DeptId = Select DeptId From Department Where DeptName = 'Computer'

INSERT INTO Student ([DeptId], [StudentName])
VALUES (@DeptId, 'TBAG')

但由于DeptId列有时不存在,我需要创建动态Sql。

所以我创建了Select语句

DECLARE @sqlCommand nvarchar(1000)
DECLARE @DeptName varchar(75)
declare @DeptId uniqueIdentifier
SET @DeptName = 'Computer'
SET @sqlCommand = 'SELECT @dept=DeptId FROM customers WHERE DeptName = @DeptName'
EXECUTE sp_executesql @sqlCommand, N'@DeptName varchar(50),@dept uniqueIdentifier  OUTPUT', @DeptName = @DeptName, @dept=@DeptId OUTPUT

但是如何编写Insert语句我没有得到

2 个答案:

答案 0 :(得分:1)

CREATE TABLE dbo.Student
(
    DeptId UNIQUEIDENTIFIER,
    StudentName VARCHAR(20)
)
GO

DECLARE @DeptId UNIQUEIDENTIFIER

IF COL_LENGTH('dbo.Department', 'DeptId') IS NOT NULL BEGIN
    SELECT @DeptId = DeptId
    FROM dbo.Department
    WHERE DeptName = 'Computer'
END

INSERT INTO dbo.Student(DeptId, StudentName)
SELECT @DeptId /* null is when DeptId is not exists */, 'TBAG'

输出 -

(1 row(s) affected)

答案 1 :(得分:0)

根据我的理解,你想为两个案例(deptid或没有deptid)准备学生表的动态插入语句

请参阅以下代码。

DECLARE @STUDENTID   INT='',--MENTION YOUR STUDENT ID VALUE AND USE THE SAME IN THE ELSE PART COMMENT OUT IF IT HAS IDENTITY
            @STUDENTNAME VARCHAR(100)=''--MENTION YOUR STUDENT NAME
    IF Col_length('dbo.Student', 'DeptId') IS NOT NULL
      BEGIN
          INSERT INTO dbo.Student
                      (DeptId,
                       StudentName)
          SELECT DeptId,
                 'TBAG'
          FROM   dbo.Department
          WHERE  DeptName = 'Computer'
      END
    ELSE
      BEGIN
          INSERT INTO dbo.Student
                      (StudentName)
          SELECT @STUDENTNAME
      END