日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > 数据库 >内容正文

数据库

自动生成Insert数据的SQL脚本

發(fā)布時(shí)間:2025/4/14 数据库 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 自动生成Insert数据的SQL脚本 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

判斷當(dāng)表存在標(biāo)識(shí)列的時(shí)候就要允許將顯式值插入表的標(biāo)識(shí)列中,設(shè)置:Set Identity_Insert TableName Off
判斷數(shù)據(jù)類型如,varchar,char,datetime,nvarchar,nchar,uniqueidentifier時(shí)候,在Insert字段中就要增加雙引號(hào),否則就不加;

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'??????????? --目標(biāo)表

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

轉(zhuǎn)載于:https://www.cnblogs.com/wei9931/archive/2008/07/10/1240093.html

總結(jié)

以上是生活随笔為你收集整理的自动生成Insert数据的SQL脚本的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。