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

首頁 > 開發 > 綜合 > 正文

將表里的數據批量生成INSERT語句的存儲過程 繼續增強版

2024-07-21 02:47:43
字體:
來源:轉載
供稿:網友
將表里的數據批量生成INSERT語句的存儲過程 繼續增強版

文章繼續 樺仔兄的文章將表里的數據批量生成INSERT語句的存儲過程 增強版繼續增強...

本來打算將該內容回復于樺仔兄的文章的下面的,但是不知為何博客園就是不讓提交!....

所以在這里貼出來吧,算作繼續增加文章中解決的:根據查詢條件自動生成插入腳本的需求,其實這種需求還是蠻常見的。

本文著重解決了文中的腳本的schema問題,給調整了下,現在腳本能自動識別出不同的schema下同名的表的語句

修改后腳本如下:

-- Author:      <樺仔>-- Blog:        <http://www.cnblogs.com/lyhabc/>-- Create date: <2014/10/18>-- Description: <根據查詢條件導出表數據的insert腳本>-- =============================================ALTER  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 statement    DECLARE @stringData NVARCHAR(MAX) --for storing the data (VALUES) related statement    DECLARE @dataType NVARCHAR(MAX) --data types returned for respective columns    DECLARE @schemaName NVARCHAR(MAX) --schema name returned from sys.schemas    DECLARE @schemaNameCount int--shema count    DECLARE @QueryString  NVARCHAR(MAX) -- provide for the whole query,     set @QueryString=' '     --如果有多個schema,選擇其中一個schema    SELECT @schemaNameCount=COUNT(*)    FROM    sys.tables t            INNER JOIN sys.schemas s ON t.schema_id = s.schema_id    WHERE   t.name = @tableName    WHILE(@schemaNameCount>0)    BEGIN    --如果有多個schema,依次指定    select @schemaName = name     from     (        SELECT ROW_NUMBER() over(order by  s.schema_id) RowID,s.name        FROM    sys.tables t                INNER JOIN sys.schemas s ON t.schema_id = s.schema_id        WHERE   t.name =  @tableName    ) as v    where RowID=@schemaNameCount    --Declare a cursor to retrieve column specific information     --for the specified table    DECLARE cursCol CURSOR FAST_FORWARD    FOR        SELECT  column_name ,                data_type        FROM    information_schema.columns        WHERE   table_name = @tableName                AND table_schema = @schemaName     OPEN cursCol    SET @string = 'INSERT INTO [' + @schemaName + '].[' + @tableName + ']('    SET @stringData = ''    DECLARE @colName NVARCHAR(500)    FETCH NEXT FROM cursCol INTO @colName, @dataType    PRINT @schemaName    PRINT @colName    IF @@fetch_status <> 0        BEGIN            PRINT 'Table ' + @tableName + ' not found, processing skipped.'            CLOSE curscol            DEALLOCATE curscol            RETURN        END    WHILE @@FETCH_STATUS = 0        BEGIN            IF @dataType IN ( 'varchar', 'char', 'nchar', 'nvarchar' )                BEGIN                       SET @stringData = @stringData + '''''''''+                            isnull(' + @colName + ','''')+'''''',''+'                END            ELSE                IF @dataType IN ( 'text', 'ntext' ) --if the datatype                                  --is text or something else                     BEGIN                        SET @stringData = @stringData + '''''''''+          isnull(cast(' + @colName + ' as nvarchar(max)),'''')+'''''',''+'                    END                ELSE                    IF @dataType = 'money' --because money doesn't get converted                        --from varchar implicitly                        BEGIN                            SET @stringData = @stringData                                + '''convert(money,''''''+        isnull(cast(' + @colName                                + ' as nvarchar(max)),''0.0000'')+''''''),''+'                        END                    ELSE                        IF @dataType = 'datetime'                            BEGIN                                SET @stringData = @stringData                                    + '''convert(datetime,''''''+        isnull(cast(' + @colName + ' as nvarchar(max)),''0'')+''''''),''+'                            END                        ELSE                            IF @dataType = 'image'                                BEGIN                                    SET @stringData = @stringData + '''''''''+       isnull(cast(convert(varbinary,' + @colName + ')        as varchar(6)),''0'')+'''''',''+'                                END                            ELSE --presuming the data type is int,bit,numeric,decimal                             BEGIN                                    SET @stringData = @stringData + '''''''''+          isnull(cast(' + @colName + ' as nvarchar(max)),''0'')+'''''',''+'                                END            SET @string = @string + '[' + @colName + ']' + ','            FETCH NEXT FROM cursCol INTO @colName, @dataType        END--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 size    PRINT @whereClause    IF ( @whereClause IS NOT NULL         AND @whereClause <> ''       )        BEGIN              SET @query = 'SELECT ''' + SUBSTRING(@string, 0, LEN(@string))                + ') VALUES(''+ ' + SUBSTRING(@stringData, 0,                                              LEN(@stringData) - 2)                + '''+'')''    FROM ' +@schemaName+'.'+ @tableName + ' WHERE ' + @whereClause            PRINT @query           -- EXEC sp_executesql @query --load and run the built query--Eventually, close and de-allocate the cursor created for columns information.        END    ELSE  BEGIN             SET @query = 'SELECT ''' + SUBSTRING(@string, 0, LEN(@string))                + ') VALUES(''+ ' + SUBSTRING(@stringData, 0,                                              LEN(@stringData) - 2)                + '''+'')''     FROM ' + @schemaName+'.'+ @tableName        END    CLOSE cursCol    DEALLOCATE cursCol    SET @schemaNameCount=@schemaNameCount-1    IF(@schemaNameCount=0)    BEGIN       SET @QueryString=@QueryString+@query    END    ELSE    BEGIN        SET @QueryString=@QueryString+@query+' UNION ALL '    END    PRINT convert(varchar(max),@schemaNameCount)+'---'+@QueryString    END    EXEC sp_executesql @QueryString --load and run the built query--Eventually, close and de-allocate the cursor created for columns information.

1、測試腳本如下:

INSERT INTO test1.[customer]([city],[region]) VALUES('2','3')InsertGenerator 'customer', null

效果如下:

2、增加篩選條件

InsertGenerator 'customer', 'city=1'

其它內容可以參照樺仔兄的原文章地址。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 遂川县| 城市| 普兰县| 宁化县| 张掖市| 鄄城县| 抚远县| 莱西市| 长子县| 宝应县| 潍坊市| 台东县| 边坝县| 天峨县| 舞阳县| 望谟县| 南阳市| 营山县| 化隆| 浦城县| 北安市| 茌平县| 林周县| 达拉特旗| 通州市| 安乡县| 安西县| 灵台县| 赤壁市| 沅江市| 桦南县| 安多县| 东山县| 耿马| 宝兴县| 朝阳县| 鱼台县| 商洛市| 嘉义县| 永济市| 赞皇县|