国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數(shù)據(jù)庫 > SQL Server > 正文

將表里的數(shù)據(jù)批量生成INSERT語句的存儲過程 增強(qiáng)版

2024-08-31 01:03:35
字體:
供稿:網(wǎng)友
這篇文章主要介紹了將表里的數(shù)據(jù)批量生成INSERT語句的存儲過程 增強(qiáng)版的相關(guān)資料,需要的朋友可以參考下
 

有時候,我們需要將某個表里的數(shù)據(jù)全部或者根據(jù)查詢條件導(dǎo)出來,遷移到另一個相同結(jié)構(gòu)的庫中

目前SQL Server里面是沒有相關(guān)的工具根據(jù)查詢條件來生成INSERT語句的,只有借助第三方工具(third party tools)

這種腳本網(wǎng)上也有很多,但是網(wǎng)上的腳本還是欠缺一些規(guī)范和功能,例如:我只想導(dǎo)出特定查詢條件的數(shù)據(jù),網(wǎng)上的腳本都是導(dǎo)出全表數(shù)據(jù)

如果表很大,對性能會有很大影響

這里有一個存儲過程(適用于SQLServer2005 或以上版本)

-- Author: <樺仔>-- Blog: <http://www.cnblogs.com/lyhabc/>-- Create date: <//>-- Description: <根據(jù)查詢條件導(dǎo)出表數(shù)據(jù)的insert腳本>-- =============================================CREATE PROCEDURE InsertGenerator(@tableName NVARCHAR(MAX),@whereClause NVARCHAR(MAX))AS --Then it includes a cursor to fetch column specific information (column name and the data type thereof) --from information_schema.columns pseudo entity and loop through for building the INSERT and VALUES clauses --of an INSERT DML statement.DECLARE @string NVARCHAR(MAX) --for storing the first half of INSERT statementDECLARE @stringData NVARCHAR(MAX) --for storing the data (VALUES) related statementDECLARE @dataType NVARCHAR(MAX) --data types returned for respective columnsDECLARE @schemaName NVARCHAR(MAX) --schema name returned from sys.schemasDECLARE @schemaNameCount int--shema countDECLARE @QueryString NVARCHAR(MAX) -- provide for the whole query, set @QueryString=' '--如果有多個schema,選擇其中一個schemaSELECT @schemaNameCount=COUNT(*)FROM sys.tables tINNER JOIN sys.schemas s ON t.schema_id = s.schema_idWHERE t.name = @tableNameWHILE(@schemaNameCount>)BEGIN--如果有多個schema,依次指定select @schemaName = name from (SELECT ROW_NUMBER() over(order by s.schema_id) RowID,s.nameFROM sys.tables tINNER JOIN sys.schemas s ON t.schema_id = s.schema_idWHERE t.name = @tableName) as vwhere RowID=@schemaNameCount--Declare a cursor to retrieve column specific information --for the specified tableDECLARE cursCol CURSOR FAST_FORWARDFORSELECT column_name ,data_typeFROM information_schema.columnsWHERE table_name = @tableNameAND table_schema = @schemaNameOPEN cursColSET @string = 'INSERT INTO [' + @schemaName + '].[' + @tableName + ']('SET @stringData = ''DECLARE @colName NVARCHAR()FETCH NEXT FROM cursCol INTO @colName, @dataTypePRINT @schemaNamePRINT @colNameIF @@fetch_status <> BEGINPRINT 'Table ' + @tableName + ' not found, processing skipped.'CLOSE curscolDEALLOCATE curscolRETURNENDWHILE @@FETCH_STATUS = BEGINIF @dataType IN ( 'varchar', 'char', 'nchar', 'nvarchar' )BEGINSET @stringData = @stringData + '''''''''+isnull(' + @colName + ','''')+'''''',''+'ENDELSEIF @dataType IN ( 'text', 'ntext' ) --if the datatype --is text or something else BEGINSET @stringData = @stringData + '''''''''+isnull(cast(' + @colName + ' as nvarchar(max)),'''')+'''''',''+'ENDELSEIF @dataType = 'money' --because money doesn't get converted --from varchar implicitlyBEGINSET @stringData = @stringData+ '''convert(money,''''''+isnull(cast(' + @colName+ ' as nvarchar(max)),''.'')+''''''),''+'ENDELSEIF @dataType = 'datetime'BEGINSET @stringData = @stringData+ '''convert(datetime,''''''+isnull(cast(' + @colName + ' as nvarchar(max)),'''')+''''''),''+'ENDELSEIF @dataType = 'image'BEGINSET @stringData = @stringData + '''''''''+isnull(cast(convert(varbinary,' + @colName + ') as varchar()),'''')+'''''',''+'ENDELSE --presuming the data type is int,bit,numeric,decimal BEGINSET @stringData = @stringData + '''''''''+isnull(cast(' + @colName + ' as nvarchar(max)),'''')+'''''',''+'ENDSET @string = @string + '[' + @colName + ']' + ','FETCH NEXT FROM cursCol INTO @colName, @dataTypeEND--After both of the clauses are built, the VALUES clause contains a trailing comma which needs to be replaced with a single quote. The prefixed clause will only face removal of the trailing comma.DECLARE @Query NVARCHAR(MAX) -- provide for the whole query, -- you may increase the sizePRINT @whereClauseIF ( @whereClause IS NOT NULLAND @whereClause <> '')BEGIN SET @query = 'SELECT ''' + SUBSTRING(@string, , LEN(@string))+ ') VALUES(''+ ' + SUBSTRING(@stringData, ,LEN(@stringData) - )+ '''+'')'' FROM ' +@schemaName+'.'+ @tableName + ' WHERE ' + @whereClausePRINT @query-- EXEC sp_executesql @query --load and run the built query--Eventually, close and de-allocate the cursor created for columns information.ENDELSEBEGIN SET @query = 'SELECT ''' + SUBSTRING(@string, , LEN(@string))+ ') VALUES(''+ ' + SUBSTRING(@stringData, ,LEN(@stringData) - )+ '''+'')'' FROM ' + @schemaName+'.'+ @tableNameENDCLOSE cursColDEALLOCATE cursColSET @schemaNameCount=@schemaNameCount-IF(@schemaNameCount=)BEGINSET @QueryString=@QueryString+@queryENDELSEBEGINSET @QueryString=@QueryString+@query+' UNION ALL 'ENDPRINT convert(varchar(max),@schemaNameCount)+'---'+@QueryStringENDEXEC sp_executesql @QueryString --load and run the built query--Eventually, close and de-allocate the cursor created for columns information. 

這里要聲明一下,如果你有多個schema,并且每個schema下面都有同一張表,那么腳本只會生成其中一個schema下面的表insert腳本

比如我現(xiàn)在有三個schema,下面都有customer這個表

CREATE TABLE dbo.[customer](city int,region int)CREATE SCHEMA testCREATE TABLE test.[customer](city int,region int)CREATE SCHEMA test1CREATE TABLE test1.[customer](city int,region int) 

在執(zhí)行腳本的時候他只會生成dbo這個schema下面的表insert腳本

INSERT INTO [dbo].[customer]([city],[region]) VALUES('1','2') 

這個腳本有一個缺陷

無論你的表的字段是什麼數(shù)據(jù)類型,導(dǎo)出來的時候只能是字符

表結(jié)構(gòu)

CREATE TABLE [dbo].[customer](city int,region int) 

導(dǎo)出來的insert腳本

INSERT INTO [dbo].[customer]([city],[region]) VALUES('1','2') 

我這里演示一下怎麼用

有兩種方式

1、導(dǎo)全表數(shù)據(jù)

InsertGenerator 'customer', null 

InsertGenerator 'customer', ' ' 

將表里的數(shù)據(jù)批量生成INSERT語句的存儲過程 增強(qiáng)版

2、根據(jù)查詢條件導(dǎo)數(shù)據(jù)

InsertGenerator 'customer', 'city=3' 

或者

InsertGenerator 'customer', 'city=3 and region=8' 

將表里的數(shù)據(jù)批量生成INSERT語句的存儲過程 增強(qiáng)版

點(diǎn)擊一下,選擇全部

將表里的數(shù)據(jù)批量生成INSERT語句的存儲過程 增強(qiáng)版

然后復(fù)制

將表里的數(shù)據(jù)批量生成INSERT語句的存儲過程 增強(qiáng)版

新建一個查詢窗口,然后粘貼

將表里的數(shù)據(jù)批量生成INSERT語句的存儲過程 增強(qiáng)版

其實(shí)SQLServer的技巧有很多

最后,大家可以看一下代碼,非常簡單,如果要支持SQLServer2000,只要改一下代碼就可以了

補(bǔ)充:創(chuàng)建一張測試表

CREATE TABLE testinsert (id INT,name VARCHAR(100),cash MONEY,dtime DATETIME)INSERT INTO [dbo].[testinsert]( [id], [name], [cash], [dtime] )VALUES ( 1, -- id - int'nihao', -- name - varchar(100)8.8, -- cash - moneyGETDATE() -- dtime - datetime)SELECT * FROM [dbo].[testinsert] 

測試

InsertGenerator 'testinsert' ,''InsertGenerator 'testinsert' ,'name=''nihao'''InsertGenerator 'testinsert' ,'name=''nihao'' and cash=8.8' 

datetime類型會有一些問題

生成的結(jié)果會自動幫你轉(zhuǎn)換

INSERT INTO [dbo].[testinsert]([id],[name],[cash],[dtime]) VALUES('1','nihao',convert(money,'8.80'),convert(datetime,'02 8 2015 5:17PM')) 

--------------------------------------------------------------------------------

群里的人共享的另一個腳本

IF OBJECT_ID('spGenInsertSQL','P') IS NOT NULL DROP PROC spGenInsertSQLGOCREATE proc spGenInsertSQL (@tablename varchar(256),@number BIGINT,@whereClause NVARCHAR(MAX))asbegindeclare @sql varchar(8000)declare @sqlValues varchar(8000)set @sql =' ('set @sqlValues = 'values (''+'select @sqlValues = @sqlValues + cols + ' + '','' + ' ,@sql = @sql + '[' + name + '],'from(select casewhen xtype in (48,52,56,59,60,62,104,106,108,122,127) then 'case when '+ name +' is null then ''NULL'' else ' + 'cast('+ name + ' as varchar)'+' end'when xtype in (58,61,40,41,42)then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'cast('+ name +' as varchar)'+ '+'''''''''+' end'when xtype in (167)then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+'''''''''+' end'when xtype in (231)then 'case when '+ name +' is null then ''NULL'' else '+'''N'''''' + ' + 'replace('+ name+','''''''','''''''''''')' + '+'''''''''+' end'when xtype in (175)then 'case when '+ name +' is null then ''NULL'' else '+''''''''' + ' + 'cast(replace('+ name+','''''''','''''''''''') as Char(' + cast(length as varchar) + '))+'''''''''+' end'when xtype in (239)then 'case when '+ name +' is null then ''NULL'' else '+'''N'''''' + ' + 'cast(replace('+ name+','''''''','''''''''''') as Char(' + cast(length as varchar) + '))+'''''''''+' end'else '''NULL'''end as Cols,namefrom syscolumns where id = object_id(@tablename)) TIF (@number!=0 AND @number IS NOT NULL)BEGINset @sql ='select top '+ CAST(@number AS VARCHAR(6000))+' ''INSERT INTO ['+ @tablename + ']' + left(@sql,len(@sql)-1)+') ' + left(@sqlValues,len(@sqlValues)-4) + ')'' from '+@tablenameprint @sqlENDELSEBEGIN set @sql ='select ''INSERT INTO ['+ @tablename + ']' + left(@sql,len(@sql)-1)+') ' + left(@sqlValues,len(@sqlValues)-4) + ')'' from '+@tablenameprint @sqlENDPRINT @whereClauseIF ( @whereClause IS NOT NULL AND @whereClause <> '')BEGINset @sql =@sql+' where '+@whereClauseprint @sqlENDexec (@sql)endGO 

調(diào)用示例

--非dbo默認(rèn)架構(gòu)需注意--支持?jǐn)?shù)據(jù)類型 :bigint,int, bit,char,datetime,date,time,decimal,money, nvarchar(50),tinyint, nvarchar(max),varchar(max),datetime2--調(diào)用示例 如果top行或者where條件為空,只需要把參數(shù)填上nullspGenInsertSQL 'customer' --表名, 2 --top 行數(shù), 'city=3 and didian=''大連'' ' --where 條件--導(dǎo)出全表 where條件為空spGenInsertSQL 'customer' --表名, null --top 行數(shù),null --where 條件INSERT INTO [Department] ([DepartmentID],[Name],[GroupName],[Company],[ModifiedDate]) values (1,N'售后部',N'銷售組',N'中國你好有限公司XX分公司','05 5 2015 5:58PM')INSERT INTO [Department] ([DepartmentID],[Name],[GroupName],[Company],[ModifiedDate]) values (2,N'售后部',N'銷售組',N'中國你好有限公司XX分公司','05 5 2015 5:58PM') 

以上所述是本文給大家分享的將表里的數(shù)據(jù)批量生成INSERT語句的存儲過程 增強(qiáng)版,希望大家喜歡。



注:相關(guān)教程知識閱讀請移步到MSSQL教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 化德县| 苍溪县| 临夏市| 普兰县| 获嘉县| 牟定县| 九龙县| 武陟县| 宝丰县| 弋阳县| 资溪县| 含山县| 和龙市| 喀喇| 中山市| 安新县| 揭东县| 安塞县| 城固县| 会宁县| 七台河市| 民勤县| 临漳县| 垣曲县| 凭祥市| 尼玛县| 涿鹿县| 石棉县| 武强县| 长治县| 噶尔县| 湖北省| 宜城市| 拜泉县| 安乡县| 汝阳县| 内江市| 碌曲县| 蓝田县| 车险| 门源|