自動產生Insert資料的SQL指令碼

來源:互聯網
上載者:User

判斷當表存在識別欄位的時候就要允許將顯式值插入表的識別欄位中,設定:Set Identity_Insert TableName Off
判斷資料類型如,varchar,char,datetime,nvarchar,nchar,uniqueidentifier時候,在Insert欄位中就要增加雙引號,否則就不加;

Use Test
Go
Declare
        @Table1 nvarchar(128),
        @Table2 nvarchar(128),
        @Sql1 nvarchar(4000),
        @Sql2 nvarchar(4000),
        @SqlIdentityInsert nvarchar(512)

Set @Table1='DutyHistory'    --源表
Set @Table2='Duty'            --目標表

IF Object_id(@Table1,'U') Is Null
    Return
If Isnull(@Table2,'')=''
    Set @Table2=@Table1

Set @SqlIdentityInsert=''
If Exists(Select 1 From sys.columns Where Object_id=Object_id(@Table1,'U'))
    Set @SqlIdentityInsert='Select ''Set Identity_Insert '+@Table2+' On '''

Select
    @Sql1=Isnull(@Sql1+',',' Insert Into '+@Table2+' (')+Quotename(name),
    @Sql2=Isnull(@Sql2+'+'',''+','Select @Sql1+'' Select ''')+'+Case When '+Quotename(name)+' Is null Then ''null'' Else '+
            Case When user_type_id In(175,61,239,231,58,98,36,167,241) Then '''''''''+Rtrim('+Quotename(name)+')+''''''''' Else 'Rtrim('+Quotename(name)+')' End +' End'
From sys.columns
Where Object_id=Object_id(@Table1,'U')

Set @Sql1=@Sql1+')'
Set @Sql2=    'Select Convert(nvarchar(max),''If Object_id('''''+@Table2+''''',''''U'''') Is Null Return;'') As SqlInsert  Union All '+
            @SqlIdentityInsert+' Union All '+
            @Sql2+' From '+Quotename(@Table1)+Case @SqlIdentityInsert When '' Then '' Else ' Union All ' End+
            Replace(@SqlIdentityInsert,' On ',' Off')

Exec sp_executesql @Sql2,N'@Sql1 nvarchar(4000)',@Sql1

Result:

SqlInsert
---------------------------------------------------------
If Object_id('Duty','U') Is Null Return;
Set Identity_Insert Duty On
 Insert Into Duty ([id],[Name],[WorkDate],[WorkHours]) Select 1,'Robert','01  1 2008 12:00AM',3.4
 Insert Into Duty ([id],[Name],[WorkDate],[WorkHours]) Select 2,'Robert','01  2 2008 12:00AM',3.4
 Insert Into Duty ([id],[Name],[WorkDate],[WorkHours]) Select 3,'Robert','01  3 2008 12:00AM',3.4
... ...
 Insert Into Duty ([id],[Name],[WorkDate],[WorkHours]) Select 58,'Robert','02 27 2008 12:00AM',4.5
 Insert Into Duty ([id],[Name],[WorkDate],[WorkHours]) Select 59,'Robert','02 28 2008 12:00AM',4.5
 Insert Into Duty ([id],[Name],[WorkDate],[WorkHours]) Select 60,'Robert','02 29 2008 12:00AM',4.5
Set Identity_Insert Duty Off

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.