为 SQL Server 表自动生成 INSERT 语句的最佳方法是什么?

发布于 2024-07-23 06:50:43 字数 429 浏览 6 评论 0原文

我们正在编写一个新的应用程序,在测试时,我们将需要一堆虚拟数据。 我通过使用 MS Access 将 excel 文件转储到相关表中来添加该数据。

我们经常想要“刷新”相关表,这意味着将它们全部删除,重新创建它们,然后运行保存的 MS Access 追加查询。

第一部分(删除和重新创建)是一个简单的 SQL 脚本,但最后一部分让我感到畏缩。 我想要一个包含大量 INSERT 的设置脚本来重新生成虚拟数据。

我现在有表格中的数据。 从该数据集自动生成大量 INSERT 语句的最佳方法是什么?

我能想到的唯一方法是将表保存到 Excel 工作表,然后编写 Excel 公式为每一行创建 INSERT,这肯定不是最好的方法。

我正在使用 2008 Management Studio 连接到 SQL Server 2005 数据库。

We are writing a new application, and while testing, we will need a bunch of dummy data. I've added that data by using MS Access to dump excel files into the relevant tables.

Every so often, we want to "refresh" the relevant tables, which means dropping them all, re-creating them, and running a saved MS Access append query.

The first part (dropping & re-creating) is an easy sql script, but the last part makes me cringe. I want a single setup script that has a bunch of INSERTs to regenerate the dummy data.

I have the data in the tables now. What is the best way to automatically generate a big list of INSERT statements from that dataset?

The only way I can think of doing it is to save the table to an excel sheet and then write an excel formula to create an INSERT for every row, which is surely not the best way.

I'm using the 2008 Management Studio to connect to a SQL Server 2005 database.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

彡翼 2024-07-30 06:50:43

Microsoft 应该宣传 SSMS 2008 的此功能。您正在寻找的功能内置于生成脚本实用程序中,但该功能默认情况下处于关闭状态,在编写表脚本时必须启用。

这是为表中的所有数据生成 INSERT 语句的快速运行,无需使用 SQL Management Studio 2008 的脚本或加载项:

  1. 右键单击数据库并转到 < strong>任务 > 生成脚本
  2. 选择要生成脚本的表(或对象)。
  3. 转到设置脚本选项选项卡,然后单击高级按钮。
  4. 常规类别中,转到要编写脚本的数据类型
  5. 有 3 个选项:仅架构仅数据架构和数据。 选择适当的选项并单击确定
    SqlDataOptions

然后,您将获得直接从 SSMS 获取数据的 CREATE TABLE 语句和所有 INSERT 语句。

Microsoft should advertise this functionality of SSMS 2008. The feature you are looking for is built into the Generate Script utility, but the functionality is turned off by default and must be enabled when scripting a table.

This is a quick run through to generate the INSERT statements for all of the data in your table, using no scripts or add-ins to SQL Management Studio 2008:

  1. Right-click on the database and go to Tasks > Generate Scripts.
  2. Select the tables (or objects) that you want to generate the script against.
  3. Go to Set scripting options tab and click on the Advanced button.
  4. In the General category, go to Type of data to script
  5. There are 3 options: Schema Only, Data Only, and Schema and Data. Select the appropriate option and click on OK.
    SqlDataOptions

You will then get the CREATE TABLE statement and all of the INSERT statements for the data straight out of SSMS.

幻想少年梦 2024-07-30 06:50:43

我们使用此存储过程 - 它允许您定位特定表并使用 where 子句。 您可以在此处找到文本。

例如,它允许您执行以下操作:

EXEC sp_generate_inserts 'titles'

从链接复制的源代码:

SET NOCOUNT ON
GO

PRINT 'Using Master database'
USE master
GO

PRINT 'Checking for the existence of this procedure'
IF (SELECT OBJECT_ID('sp_generate_inserts','P')) IS NOT NULL --means, the procedure already exists
    BEGIN
        PRINT 'Procedure already exists. So, dropping it'
        DROP PROC sp_generate_inserts
    END
GO

--Turn system object marking on
EXEC master.dbo.sp_MS_upd_sysobj_category 1
GO

CREATE PROC sp_generate_inserts
(
    @table_name varchar(776),       -- The table/view for which the INSERT statements will be generated using the existing data
    @target_table varchar(776) = NULL,  -- Use this parameter to specify a different table name into which the data will be inserted
    @include_column_list bit = 1,       -- Use this parameter to include/ommit column list in the generated INSERT statement
    @from varchar(800) = NULL,      -- Use this parameter to filter the rows based on a filter condition (using WHERE)
    @include_timestamp bit = 0,         -- Specify 1 for this parameter, if you want to include the TIMESTAMP/ROWVERSION column's data in the INSERT statement
    @debug_mode bit = 0,            -- If @debug_mode is set to 1, the SQL statements constructed by this procedure will be printed for later examination
    @owner varchar(64) = NULL,      -- Use this parameter if you are not the owner of the table
    @ommit_images bit = 0,          -- Use this parameter to generate INSERT statements by omitting the 'image' columns
    @ommit_identity bit = 0,        -- Use this parameter to ommit the identity columns
    @top int = NULL,            -- Use this parameter to generate INSERT statements only for the TOP n rows
    @cols_to_include varchar(8000) = NULL,  -- List of columns to be included in the INSERT statement
    @cols_to_exclude varchar(8000) = NULL,  -- List of columns to be excluded from the INSERT statement
    @disable_constraints bit = 0,       -- When 1, disables foreign key constraints and enables them after the INSERT statements
    @ommit_computed_cols bit = 0        -- When 1, computed columns will not be included in the INSERT statement

)
AS
BEGIN

/***********************************************************************************************************
Procedure:  sp_generate_inserts  (Build 22) 
        (Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.)

Purpose:    To generate INSERT statements from existing data. 
        These INSERTS can be executed to regenerate the data at some other location.
        This procedure is also useful to create a database setup, where in you can 
        script your data along with your table definitions.

Written by: Narayana Vyas Kondreddi
            http://vyaskn.tripod.com
            http://vyaskn.tripod.com/code/generate_inserts.txt

Acknowledgements:
        Divya Kalra -- For beta testing
        Mark Charsley   -- For reporting a problem with scripting uniqueidentifier columns with NULL values
        Artur Zeygman   -- For helping me simplify a bit of code for handling non-dbo owned tables
        Joris Laperre   -- For reporting a regression bug in handling text/ntext columns

Tested on:  SQL Server 7.0 and SQL Server 2000

Date created:   January 17th 2001 21:52 GMT

Date modified:  May 1st 2002 19:50 GMT

Email:      [email protected]

NOTE:       This procedure may not work with tables with too many columns.
        Results can be unpredictable with huge text columns or SQL Server 2000's sql_variant data types
        Whenever possible, Use @include_column_list parameter to ommit column list in the INSERT statement, for better results
        IMPORTANT: This procedure is not tested with internation data (Extended characters or Unicode). If needed
        you might want to convert the datatypes of character variables in this procedure to their respective unicode counterparts
        like nchar and nvarchar


Example 1:  To generate INSERT statements for table 'titles':

        EXEC sp_generate_inserts 'titles'

Example 2:  To ommit the column list in the INSERT statement: (Column list is included by default)
        IMPORTANT: If you have too many columns, you are advised to ommit column list, as shown below,
        to avoid erroneous results

        EXEC sp_generate_inserts 'titles', @include_column_list = 0

Example 3:  To generate INSERT statements for 'titlesCopy' table from 'titles' table:

        EXEC sp_generate_inserts 'titles', 'titlesCopy'

Example 4:  To generate INSERT statements for 'titles' table for only those titles 
        which contain the word 'Computer' in them:
        NOTE: Do not complicate the FROM or WHERE clause here. It's assumed that you are good with T-SQL if you are using this parameter

        EXEC sp_generate_inserts 'titles', @from = "from titles where title like '%Computer%'"

Example 5:  To specify that you want to include TIMESTAMP column's data as well in the INSERT statement:
        (By default TIMESTAMP column's data is not scripted)

        EXEC sp_generate_inserts 'titles', @include_timestamp = 1

Example 6:  To print the debug information:

        EXEC sp_generate_inserts 'titles', @debug_mode = 1

Example 7:  If you are not the owner of the table, use @owner parameter to specify the owner name
        To use this option, you must have SELECT permissions on that table

        EXEC sp_generate_inserts Nickstable, @owner = 'Nick'

Example 8:  To generate INSERT statements for the rest of the columns excluding images
        When using this otion, DO NOT set @include_column_list parameter to 0.

        EXEC sp_generate_inserts imgtable, @ommit_images = 1

Example 9:  To generate INSERT statements excluding (ommiting) IDENTITY columns:
        (By default IDENTITY columns are included in the INSERT statement)

        EXEC sp_generate_inserts mytable, @ommit_identity = 1

Example 10:     To generate INSERT statements for the TOP 10 rows in the table:

        EXEC sp_generate_inserts mytable, @top = 10

Example 11:     To generate INSERT statements with only those columns you want:

        EXEC sp_generate_inserts titles, @cols_to_include = "'title','title_id','au_id'"

Example 12:     To generate INSERT statements by omitting certain columns:

        EXEC sp_generate_inserts titles, @cols_to_exclude = "'title','title_id','au_id'"

Example 13: To avoid checking the foreign key constraints while loading data with INSERT statements:

        EXEC sp_generate_inserts titles, @disable_constraints = 1

Example 14:     To exclude computed columns from the INSERT statement:
        EXEC sp_generate_inserts MyTable, @ommit_computed_cols = 1
***********************************************************************************************************/

SET NOCOUNT ON

--Making sure user only uses either @cols_to_include or @cols_to_exclude
IF ((@cols_to_include IS NOT NULL) AND (@cols_to_exclude IS NOT NULL))
    BEGIN
        RAISERROR('Use either @cols_to_include or @cols_to_exclude. Do not use both the parameters at once',16,1)
        RETURN -1 --Failure. Reason: Both @cols_to_include and @cols_to_exclude parameters are specified
    END

--Making sure the @cols_to_include and @cols_to_exclude parameters are receiving values in proper format
IF ((@cols_to_include IS NOT NULL) AND (PATINDEX('''%''',@cols_to_include) = 0))
    BEGIN
        RAISERROR('Invalid use of @cols_to_include property',16,1)
        PRINT 'Specify column names surrounded by single quotes and separated by commas'
        PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_include = "''title_id'',''title''"'
        RETURN -1 --Failure. Reason: Invalid use of @cols_to_include property
    END

IF ((@cols_to_exclude IS NOT NULL) AND (PATINDEX('''%''',@cols_to_exclude) = 0))
    BEGIN
        RAISERROR('Invalid use of @cols_to_exclude property',16,1)
        PRINT 'Specify column names surrounded by single quotes and separated by commas'
        PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_exclude = "''title_id'',''title''"'
        RETURN -1 --Failure. Reason: Invalid use of @cols_to_exclude property
    END


--Checking to see if the database name is specified along wih the table name
--Your database context should be local to the table for which you want to generate INSERT statements
--specifying the database name is not allowed
IF (PARSENAME(@table_name,3)) IS NOT NULL
    BEGIN
        RAISERROR('Do not specify the database name. Be in the required database and just specify the table name.',16,1)
        RETURN -1 --Failure. Reason: Database name is specified along with the table name, which is not allowed
    END

--Checking for the existence of 'user table' or 'view'
--This procedure is not written to work on system tables
--To script the data in system tables, just create a view on the system tables and script the view instead

IF @owner IS NULL
    BEGIN
        IF ((OBJECT_ID(@table_name,'U') IS NULL) AND (OBJECT_ID(@table_name,'V') IS NULL)) 
            BEGIN
                RAISERROR('User table or view not found.',16,1)
                PRINT 'You may see this error, if you are not the owner of this table or view. In that case use @owner parameter to specify the owner name.'
                PRINT 'Make sure you have SELECT permission on that table or view.'
                RETURN -1 --Failure. Reason: There is no user table or view with this name
            END
    END
ELSE
    BEGIN
        IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @table_name AND (TABLE_TYPE = 'BASE TABLE' OR TABLE_TYPE = 'VIEW') AND TABLE_SCHEMA = @owner)
            BEGIN
                RAISERROR('User table or view not found.',16,1)
                PRINT 'You may see this error, if you are not the owner of this table. In that case use @owner parameter to specify the owner name.'
                PRINT 'Make sure you have SELECT permission on that table or view.'
                RETURN -1 --Failure. Reason: There is no user table or view with this name      
            END
    END

--Variable declarations
DECLARE     @Column_ID int,         
        @Column_List varchar(8000), 
        @Column_Name varchar(128), 
        @Start_Insert varchar(786), 
        @Data_Type varchar(128), 
        @Actual_Values varchar(8000),   --This is the string that will be finally executed to generate INSERT statements
        @IDN varchar(128)       --Will contain the IDENTITY column's name in the table

--Variable Initialization
SET @IDN = ''
SET @Column_ID = 0
SET @Column_Name = ''
SET @Column_List = ''
SET @Actual_Values = ''

IF @owner IS NULL 
    BEGIN
        SET @Start_Insert = 'INSERT INTO ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' 
    END
ELSE
    BEGIN
        SET @Start_Insert = 'INSERT ' + '[' + LTRIM(RTRIM(@owner)) + '].' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']'      
    END


--To get the first column's ID

SELECT  @Column_ID = MIN(ORDINAL_POSITION)  
FROM    INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
WHERE   TABLE_NAME = @table_name AND
(@owner IS NULL OR TABLE_SCHEMA = @owner)



--Loop through all the columns of the table, to get the column names and their data types
WHILE @Column_ID IS NOT NULL
    BEGIN
        SELECT  @Column_Name = QUOTENAME(COLUMN_NAME), 
        @Data_Type = DATA_TYPE 
        FROM    INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
        WHERE   ORDINAL_POSITION = @Column_ID AND 
        TABLE_NAME = @table_name AND
        (@owner IS NULL OR TABLE_SCHEMA = @owner)



        IF @cols_to_include IS NOT NULL --Selecting only user specified columns
        BEGIN
            IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_include) = 0 
            BEGIN
                GOTO SKIP_LOOP
            END
        END

        IF @cols_to_exclude IS NOT NULL --Selecting only user specified columns
        BEGIN
            IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_exclude) <> 0 
            BEGIN
                GOTO SKIP_LOOP
            END
        END

        --Making sure to output SET IDENTITY_INSERT ON/OFF in case the table has an IDENTITY column
        IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsIdentity')) = 1 
        BEGIN
            IF @ommit_identity = 0 --Determing whether to include or exclude the IDENTITY column
                SET @IDN = @Column_Name
            ELSE
                GOTO SKIP_LOOP          
        END

        --Making sure whether to output computed columns or not
        IF @ommit_computed_cols = 1
        BEGIN
            IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsComputed')) = 1 
            BEGIN
                GOTO SKIP_LOOP                  
            END
        END

        --Tables with columns of IMAGE data type are not supported for obvious reasons
        IF(@Data_Type in ('image'))
            BEGIN
                IF (@ommit_images = 0)
                    BEGIN
                        RAISERROR('Tables with image columns are not supported.',16,1)
                        PRINT 'Use @ommit_images = 1 parameter to generate INSERTs for the rest of the columns.'
                        PRINT 'DO NOT ommit Column List in the INSERT statements. If you ommit column list using @include_column_list=0, the generated INSERTs will fail.'
                        RETURN -1 --Failure. Reason: There is a column with image data type
                    END
                ELSE
                    BEGIN
                    GOTO SKIP_LOOP
                    END
            END

        --Determining the data type of the column and depending on the data type, the VALUES part of
        --the INSERT statement is generated. Care is taken to handle columns with NULL values. Also
        --making sure, not to lose any data from flot, real, money, smallmomey, datetime columns
        SET @Actual_Values = @Actual_Values  +
        CASE 
            WHEN @Data_Type IN ('char','varchar','nchar','nvarchar') 
                THEN 
                    'COALESCE('''''''' + REPLACE(RTRIM(' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
            WHEN @Data_Type IN ('datetime','smalldatetime') 
                THEN 
                    'COALESCE('''''''' + RTRIM(CONVERT(char,' + @Column_Name + ',109))+'''''''',''NULL'')'
            WHEN @Data_Type IN ('uniqueidentifier') 
                THEN  
                    'COALESCE('''''''' + REPLACE(CONVERT(char(255),RTRIM(' + @Column_Name + ')),'''''''','''''''''''')+'''''''',''NULL'')'
            WHEN @Data_Type IN ('text','ntext') 
                THEN  
                    'COALESCE('''''''' + REPLACE(CONVERT(char(8000),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'                    
            WHEN @Data_Type IN ('binary','varbinary') 
                THEN  
                    'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'  
            WHEN @Data_Type IN ('timestamp','rowversion') 
                THEN  
                    CASE 
                        WHEN @include_timestamp = 0 
                            THEN 
                                '''DEFAULT''' 
                            ELSE 
                                'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'  
                    END
            WHEN @Data_Type IN ('float','real','money','smallmoney')
                THEN
                    'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' +  @Column_Name  + ',2)' + ')),''NULL'')' 
            ELSE 
                'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' +  @Column_Name  + ')' + ')),''NULL'')' 
        END   + '+' +  ''',''' + ' + '

        --Generating the column list for the INSERT statement
        SET @Column_List = @Column_List +  @Column_Name + ','   

        SKIP_LOOP: --The label used in GOTO

        SELECT  @Column_ID = MIN(ORDINAL_POSITION) 
        FROM    INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
        WHERE   TABLE_NAME = @table_name AND 
        ORDINAL_POSITION > @Column_ID AND
        (@owner IS NULL OR TABLE_SCHEMA = @owner)


    --Loop ends here!
    END

--To get rid of the extra characters that got concatenated during the last run through the loop
SET @Column_List = LEFT(@Column_List,len(@Column_List) - 1)
SET @Actual_Values = LEFT(@Actual_Values,len(@Actual_Values) - 6)

IF LTRIM(@Column_List) = '' 
    BEGIN
        RAISERROR('No columns to select. There should at least be one column to generate the output',16,1)
        RETURN -1 --Failure. Reason: Looks like all the columns are ommitted using the @cols_to_exclude parameter
    END

--Forming the final string that will be executed, to output the INSERT statements
IF (@include_column_list <> 0)
    BEGIN
        SET @Actual_Values = 
            'SELECT ' +  
            CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END + 
            '''' + RTRIM(@Start_Insert) + 
            ' ''+' + '''(' + RTRIM(@Column_List) +  '''+' + ''')''' + 
            ' +''VALUES(''+ ' +  @Actual_Values  + '+'')''' + ' ' + 
            COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')
    END
ELSE IF (@include_column_list = 0)
    BEGIN
        SET @Actual_Values = 
            'SELECT ' + 
            CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END + 
            '''' + RTRIM(@Start_Insert) + 
            ' '' +''VALUES(''+ ' +  @Actual_Values + '+'')''' + ' ' + 
            COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')
    END 

--Determining whether to ouput any debug information
IF @debug_mode =1
    BEGIN
        PRINT '/*****START OF DEBUG INFORMATION*****'
        PRINT 'Beginning of the INSERT statement:'
        PRINT @Start_Insert
        PRINT ''
        PRINT 'The column list:'
        PRINT @Column_List
        PRINT ''
        PRINT 'The SELECT statement executed to generate the INSERTs'
        PRINT @Actual_Values
        PRINT ''
        PRINT '*****END OF DEBUG INFORMATION*****/'
        PRINT ''
    END

PRINT '--INSERTs generated by ''sp_generate_inserts'' stored procedure written by Vyas'
PRINT '--Build number: 22'
PRINT '--Problems/Suggestions? Contact Vyas @ [email protected]'
PRINT '--http://vyaskn.tripod.com'
PRINT ''
PRINT 'SET NOCOUNT ON'
PRINT ''


--Determining whether to print IDENTITY_INSERT or not
IF (@IDN <> '')
    BEGIN
        PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' ON'
        PRINT 'GO'
        PRINT ''
    END


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
    BEGIN
        IF @owner IS NULL
            BEGIN
                SELECT  'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
            END
        ELSE
            BEGIN
                SELECT  'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
            END

        PRINT 'GO'
    END

PRINT ''
PRINT 'PRINT ''Inserting values into ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' + ''''


--All the hard work pays off here!!! You'll get your INSERT statements, when the next line executes!
EXEC (@Actual_Values)

PRINT 'PRINT ''Done'''
PRINT ''


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
    BEGIN
        IF @owner IS NULL
            BEGIN
                SELECT  'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL'  AS '--Code to enable the previously disabled constraints'
            END
        ELSE
            BEGIN
                SELECT  'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL' AS '--Code to enable the previously disabled constraints'
            END

        PRINT 'GO'
    END

PRINT ''
IF (@IDN <> '')
    BEGIN
        PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' OFF'
        PRINT 'GO'
    END

PRINT 'SET NOCOUNT OFF'


SET NOCOUNT OFF
RETURN 0 --Success. We are done!
END

GO

PRINT 'Created the procedure'
GO


--Turn system object marking off
EXEC master.dbo.sp_MS_upd_sysobj_category 2
GO

PRINT 'Granting EXECUTE permission on sp_generate_inserts to all users'
GRANT EXEC ON sp_generate_inserts TO public

SET NOCOUNT OFF
GO

PRINT 'Done'

We use this stored procedure - it allows you to target specific tables, and use where clauses. You can find the text here.

For example, it lets you do this:

EXEC sp_generate_inserts 'titles'

Source code copied from link:

SET NOCOUNT ON
GO

PRINT 'Using Master database'
USE master
GO

PRINT 'Checking for the existence of this procedure'
IF (SELECT OBJECT_ID('sp_generate_inserts','P')) IS NOT NULL --means, the procedure already exists
    BEGIN
        PRINT 'Procedure already exists. So, dropping it'
        DROP PROC sp_generate_inserts
    END
GO

--Turn system object marking on
EXEC master.dbo.sp_MS_upd_sysobj_category 1
GO

CREATE PROC sp_generate_inserts
(
    @table_name varchar(776),       -- The table/view for which the INSERT statements will be generated using the existing data
    @target_table varchar(776) = NULL,  -- Use this parameter to specify a different table name into which the data will be inserted
    @include_column_list bit = 1,       -- Use this parameter to include/ommit column list in the generated INSERT statement
    @from varchar(800) = NULL,      -- Use this parameter to filter the rows based on a filter condition (using WHERE)
    @include_timestamp bit = 0,         -- Specify 1 for this parameter, if you want to include the TIMESTAMP/ROWVERSION column's data in the INSERT statement
    @debug_mode bit = 0,            -- If @debug_mode is set to 1, the SQL statements constructed by this procedure will be printed for later examination
    @owner varchar(64) = NULL,      -- Use this parameter if you are not the owner of the table
    @ommit_images bit = 0,          -- Use this parameter to generate INSERT statements by omitting the 'image' columns
    @ommit_identity bit = 0,        -- Use this parameter to ommit the identity columns
    @top int = NULL,            -- Use this parameter to generate INSERT statements only for the TOP n rows
    @cols_to_include varchar(8000) = NULL,  -- List of columns to be included in the INSERT statement
    @cols_to_exclude varchar(8000) = NULL,  -- List of columns to be excluded from the INSERT statement
    @disable_constraints bit = 0,       -- When 1, disables foreign key constraints and enables them after the INSERT statements
    @ommit_computed_cols bit = 0        -- When 1, computed columns will not be included in the INSERT statement

)
AS
BEGIN

/***********************************************************************************************************
Procedure:  sp_generate_inserts  (Build 22) 
        (Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.)

Purpose:    To generate INSERT statements from existing data. 
        These INSERTS can be executed to regenerate the data at some other location.
        This procedure is also useful to create a database setup, where in you can 
        script your data along with your table definitions.

Written by: Narayana Vyas Kondreddi
            http://vyaskn.tripod.com
            http://vyaskn.tripod.com/code/generate_inserts.txt

Acknowledgements:
        Divya Kalra -- For beta testing
        Mark Charsley   -- For reporting a problem with scripting uniqueidentifier columns with NULL values
        Artur Zeygman   -- For helping me simplify a bit of code for handling non-dbo owned tables
        Joris Laperre   -- For reporting a regression bug in handling text/ntext columns

Tested on:  SQL Server 7.0 and SQL Server 2000

Date created:   January 17th 2001 21:52 GMT

Date modified:  May 1st 2002 19:50 GMT

Email:      [email protected]

NOTE:       This procedure may not work with tables with too many columns.
        Results can be unpredictable with huge text columns or SQL Server 2000's sql_variant data types
        Whenever possible, Use @include_column_list parameter to ommit column list in the INSERT statement, for better results
        IMPORTANT: This procedure is not tested with internation data (Extended characters or Unicode). If needed
        you might want to convert the datatypes of character variables in this procedure to their respective unicode counterparts
        like nchar and nvarchar


Example 1:  To generate INSERT statements for table 'titles':

        EXEC sp_generate_inserts 'titles'

Example 2:  To ommit the column list in the INSERT statement: (Column list is included by default)
        IMPORTANT: If you have too many columns, you are advised to ommit column list, as shown below,
        to avoid erroneous results

        EXEC sp_generate_inserts 'titles', @include_column_list = 0

Example 3:  To generate INSERT statements for 'titlesCopy' table from 'titles' table:

        EXEC sp_generate_inserts 'titles', 'titlesCopy'

Example 4:  To generate INSERT statements for 'titles' table for only those titles 
        which contain the word 'Computer' in them:
        NOTE: Do not complicate the FROM or WHERE clause here. It's assumed that you are good with T-SQL if you are using this parameter

        EXEC sp_generate_inserts 'titles', @from = "from titles where title like '%Computer%'"

Example 5:  To specify that you want to include TIMESTAMP column's data as well in the INSERT statement:
        (By default TIMESTAMP column's data is not scripted)

        EXEC sp_generate_inserts 'titles', @include_timestamp = 1

Example 6:  To print the debug information:

        EXEC sp_generate_inserts 'titles', @debug_mode = 1

Example 7:  If you are not the owner of the table, use @owner parameter to specify the owner name
        To use this option, you must have SELECT permissions on that table

        EXEC sp_generate_inserts Nickstable, @owner = 'Nick'

Example 8:  To generate INSERT statements for the rest of the columns excluding images
        When using this otion, DO NOT set @include_column_list parameter to 0.

        EXEC sp_generate_inserts imgtable, @ommit_images = 1

Example 9:  To generate INSERT statements excluding (ommiting) IDENTITY columns:
        (By default IDENTITY columns are included in the INSERT statement)

        EXEC sp_generate_inserts mytable, @ommit_identity = 1

Example 10:     To generate INSERT statements for the TOP 10 rows in the table:

        EXEC sp_generate_inserts mytable, @top = 10

Example 11:     To generate INSERT statements with only those columns you want:

        EXEC sp_generate_inserts titles, @cols_to_include = "'title','title_id','au_id'"

Example 12:     To generate INSERT statements by omitting certain columns:

        EXEC sp_generate_inserts titles, @cols_to_exclude = "'title','title_id','au_id'"

Example 13: To avoid checking the foreign key constraints while loading data with INSERT statements:

        EXEC sp_generate_inserts titles, @disable_constraints = 1

Example 14:     To exclude computed columns from the INSERT statement:
        EXEC sp_generate_inserts MyTable, @ommit_computed_cols = 1
***********************************************************************************************************/

SET NOCOUNT ON

--Making sure user only uses either @cols_to_include or @cols_to_exclude
IF ((@cols_to_include IS NOT NULL) AND (@cols_to_exclude IS NOT NULL))
    BEGIN
        RAISERROR('Use either @cols_to_include or @cols_to_exclude. Do not use both the parameters at once',16,1)
        RETURN -1 --Failure. Reason: Both @cols_to_include and @cols_to_exclude parameters are specified
    END

--Making sure the @cols_to_include and @cols_to_exclude parameters are receiving values in proper format
IF ((@cols_to_include IS NOT NULL) AND (PATINDEX('''%''',@cols_to_include) = 0))
    BEGIN
        RAISERROR('Invalid use of @cols_to_include property',16,1)
        PRINT 'Specify column names surrounded by single quotes and separated by commas'
        PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_include = "''title_id'',''title''"'
        RETURN -1 --Failure. Reason: Invalid use of @cols_to_include property
    END

IF ((@cols_to_exclude IS NOT NULL) AND (PATINDEX('''%''',@cols_to_exclude) = 0))
    BEGIN
        RAISERROR('Invalid use of @cols_to_exclude property',16,1)
        PRINT 'Specify column names surrounded by single quotes and separated by commas'
        PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_exclude = "''title_id'',''title''"'
        RETURN -1 --Failure. Reason: Invalid use of @cols_to_exclude property
    END


--Checking to see if the database name is specified along wih the table name
--Your database context should be local to the table for which you want to generate INSERT statements
--specifying the database name is not allowed
IF (PARSENAME(@table_name,3)) IS NOT NULL
    BEGIN
        RAISERROR('Do not specify the database name. Be in the required database and just specify the table name.',16,1)
        RETURN -1 --Failure. Reason: Database name is specified along with the table name, which is not allowed
    END

--Checking for the existence of 'user table' or 'view'
--This procedure is not written to work on system tables
--To script the data in system tables, just create a view on the system tables and script the view instead

IF @owner IS NULL
    BEGIN
        IF ((OBJECT_ID(@table_name,'U') IS NULL) AND (OBJECT_ID(@table_name,'V') IS NULL)) 
            BEGIN
                RAISERROR('User table or view not found.',16,1)
                PRINT 'You may see this error, if you are not the owner of this table or view. In that case use @owner parameter to specify the owner name.'
                PRINT 'Make sure you have SELECT permission on that table or view.'
                RETURN -1 --Failure. Reason: There is no user table or view with this name
            END
    END
ELSE
    BEGIN
        IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @table_name AND (TABLE_TYPE = 'BASE TABLE' OR TABLE_TYPE = 'VIEW') AND TABLE_SCHEMA = @owner)
            BEGIN
                RAISERROR('User table or view not found.',16,1)
                PRINT 'You may see this error, if you are not the owner of this table. In that case use @owner parameter to specify the owner name.'
                PRINT 'Make sure you have SELECT permission on that table or view.'
                RETURN -1 --Failure. Reason: There is no user table or view with this name      
            END
    END

--Variable declarations
DECLARE     @Column_ID int,         
        @Column_List varchar(8000), 
        @Column_Name varchar(128), 
        @Start_Insert varchar(786), 
        @Data_Type varchar(128), 
        @Actual_Values varchar(8000),   --This is the string that will be finally executed to generate INSERT statements
        @IDN varchar(128)       --Will contain the IDENTITY column's name in the table

--Variable Initialization
SET @IDN = ''
SET @Column_ID = 0
SET @Column_Name = ''
SET @Column_List = ''
SET @Actual_Values = ''

IF @owner IS NULL 
    BEGIN
        SET @Start_Insert = 'INSERT INTO ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' 
    END
ELSE
    BEGIN
        SET @Start_Insert = 'INSERT ' + '[' + LTRIM(RTRIM(@owner)) + '].' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']'      
    END


--To get the first column's ID

SELECT  @Column_ID = MIN(ORDINAL_POSITION)  
FROM    INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
WHERE   TABLE_NAME = @table_name AND
(@owner IS NULL OR TABLE_SCHEMA = @owner)



--Loop through all the columns of the table, to get the column names and their data types
WHILE @Column_ID IS NOT NULL
    BEGIN
        SELECT  @Column_Name = QUOTENAME(COLUMN_NAME), 
        @Data_Type = DATA_TYPE 
        FROM    INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
        WHERE   ORDINAL_POSITION = @Column_ID AND 
        TABLE_NAME = @table_name AND
        (@owner IS NULL OR TABLE_SCHEMA = @owner)



        IF @cols_to_include IS NOT NULL --Selecting only user specified columns
        BEGIN
            IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_include) = 0 
            BEGIN
                GOTO SKIP_LOOP
            END
        END

        IF @cols_to_exclude IS NOT NULL --Selecting only user specified columns
        BEGIN
            IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_exclude) <> 0 
            BEGIN
                GOTO SKIP_LOOP
            END
        END

        --Making sure to output SET IDENTITY_INSERT ON/OFF in case the table has an IDENTITY column
        IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsIdentity')) = 1 
        BEGIN
            IF @ommit_identity = 0 --Determing whether to include or exclude the IDENTITY column
                SET @IDN = @Column_Name
            ELSE
                GOTO SKIP_LOOP          
        END

        --Making sure whether to output computed columns or not
        IF @ommit_computed_cols = 1
        BEGIN
            IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsComputed')) = 1 
            BEGIN
                GOTO SKIP_LOOP                  
            END
        END

        --Tables with columns of IMAGE data type are not supported for obvious reasons
        IF(@Data_Type in ('image'))
            BEGIN
                IF (@ommit_images = 0)
                    BEGIN
                        RAISERROR('Tables with image columns are not supported.',16,1)
                        PRINT 'Use @ommit_images = 1 parameter to generate INSERTs for the rest of the columns.'
                        PRINT 'DO NOT ommit Column List in the INSERT statements. If you ommit column list using @include_column_list=0, the generated INSERTs will fail.'
                        RETURN -1 --Failure. Reason: There is a column with image data type
                    END
                ELSE
                    BEGIN
                    GOTO SKIP_LOOP
                    END
            END

        --Determining the data type of the column and depending on the data type, the VALUES part of
        --the INSERT statement is generated. Care is taken to handle columns with NULL values. Also
        --making sure, not to lose any data from flot, real, money, smallmomey, datetime columns
        SET @Actual_Values = @Actual_Values  +
        CASE 
            WHEN @Data_Type IN ('char','varchar','nchar','nvarchar') 
                THEN 
                    'COALESCE('''''''' + REPLACE(RTRIM(' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
            WHEN @Data_Type IN ('datetime','smalldatetime') 
                THEN 
                    'COALESCE('''''''' + RTRIM(CONVERT(char,' + @Column_Name + ',109))+'''''''',''NULL'')'
            WHEN @Data_Type IN ('uniqueidentifier') 
                THEN  
                    'COALESCE('''''''' + REPLACE(CONVERT(char(255),RTRIM(' + @Column_Name + ')),'''''''','''''''''''')+'''''''',''NULL'')'
            WHEN @Data_Type IN ('text','ntext') 
                THEN  
                    'COALESCE('''''''' + REPLACE(CONVERT(char(8000),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'                    
            WHEN @Data_Type IN ('binary','varbinary') 
                THEN  
                    'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'  
            WHEN @Data_Type IN ('timestamp','rowversion') 
                THEN  
                    CASE 
                        WHEN @include_timestamp = 0 
                            THEN 
                                '''DEFAULT''' 
                            ELSE 
                                'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'  
                    END
            WHEN @Data_Type IN ('float','real','money','smallmoney')
                THEN
                    'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' +  @Column_Name  + ',2)' + ')),''NULL'')' 
            ELSE 
                'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' +  @Column_Name  + ')' + ')),''NULL'')' 
        END   + '+' +  ''',''' + ' + '

        --Generating the column list for the INSERT statement
        SET @Column_List = @Column_List +  @Column_Name + ','   

        SKIP_LOOP: --The label used in GOTO

        SELECT  @Column_ID = MIN(ORDINAL_POSITION) 
        FROM    INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
        WHERE   TABLE_NAME = @table_name AND 
        ORDINAL_POSITION > @Column_ID AND
        (@owner IS NULL OR TABLE_SCHEMA = @owner)


    --Loop ends here!
    END

--To get rid of the extra characters that got concatenated during the last run through the loop
SET @Column_List = LEFT(@Column_List,len(@Column_List) - 1)
SET @Actual_Values = LEFT(@Actual_Values,len(@Actual_Values) - 6)

IF LTRIM(@Column_List) = '' 
    BEGIN
        RAISERROR('No columns to select. There should at least be one column to generate the output',16,1)
        RETURN -1 --Failure. Reason: Looks like all the columns are ommitted using the @cols_to_exclude parameter
    END

--Forming the final string that will be executed, to output the INSERT statements
IF (@include_column_list <> 0)
    BEGIN
        SET @Actual_Values = 
            'SELECT ' +  
            CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END + 
            '''' + RTRIM(@Start_Insert) + 
            ' ''+' + '''(' + RTRIM(@Column_List) +  '''+' + ''')''' + 
            ' +''VALUES(''+ ' +  @Actual_Values  + '+'')''' + ' ' + 
            COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')
    END
ELSE IF (@include_column_list = 0)
    BEGIN
        SET @Actual_Values = 
            'SELECT ' + 
            CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END + 
            '''' + RTRIM(@Start_Insert) + 
            ' '' +''VALUES(''+ ' +  @Actual_Values + '+'')''' + ' ' + 
            COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')
    END 

--Determining whether to ouput any debug information
IF @debug_mode =1
    BEGIN
        PRINT '/*****START OF DEBUG INFORMATION*****'
        PRINT 'Beginning of the INSERT statement:'
        PRINT @Start_Insert
        PRINT ''
        PRINT 'The column list:'
        PRINT @Column_List
        PRINT ''
        PRINT 'The SELECT statement executed to generate the INSERTs'
        PRINT @Actual_Values
        PRINT ''
        PRINT '*****END OF DEBUG INFORMATION*****/'
        PRINT ''
    END

PRINT '--INSERTs generated by ''sp_generate_inserts'' stored procedure written by Vyas'
PRINT '--Build number: 22'
PRINT '--Problems/Suggestions? Contact Vyas @ [email protected]'
PRINT '--http://vyaskn.tripod.com'
PRINT ''
PRINT 'SET NOCOUNT ON'
PRINT ''


--Determining whether to print IDENTITY_INSERT or not
IF (@IDN <> '')
    BEGIN
        PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' ON'
        PRINT 'GO'
        PRINT ''
    END


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
    BEGIN
        IF @owner IS NULL
            BEGIN
                SELECT  'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
            END
        ELSE
            BEGIN
                SELECT  'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
            END

        PRINT 'GO'
    END

PRINT ''
PRINT 'PRINT ''Inserting values into ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' + ''''


--All the hard work pays off here!!! You'll get your INSERT statements, when the next line executes!
EXEC (@Actual_Values)

PRINT 'PRINT ''Done'''
PRINT ''


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
    BEGIN
        IF @owner IS NULL
            BEGIN
                SELECT  'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL'  AS '--Code to enable the previously disabled constraints'
            END
        ELSE
            BEGIN
                SELECT  'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL' AS '--Code to enable the previously disabled constraints'
            END

        PRINT 'GO'
    END

PRINT ''
IF (@IDN <> '')
    BEGIN
        PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' OFF'
        PRINT 'GO'
    END

PRINT 'SET NOCOUNT OFF'


SET NOCOUNT OFF
RETURN 0 --Success. We are done!
END

GO

PRINT 'Created the procedure'
GO


--Turn system object marking off
EXEC master.dbo.sp_MS_upd_sysobj_category 2
GO

PRINT 'Granting EXECUTE permission on sp_generate_inserts to all users'
GRANT EXEC ON sp_generate_inserts TO public

SET NOCOUNT OFF
GO

PRINT 'Done'
有深☉意 2024-07-30 06:50:43

这也可以使用 Visual Studio 来完成(至少在 2013 版本以后)。

在 VS 2013 中,还可以过滤插入语句所基于的行列表,据我所知,这在 SSMS 中是不可能的。

执行以下步骤:

  • 打开“SQL Server 对象资源管理器”窗口(菜单:/View/SQL Server 对象资源管理器)
  • 打开/展开数据库及其表
  • 右键单击​​表并从上下文菜单中选择“查看数据”
  • 这将显示主区域中的数据
  • 可选步骤: 单击筛选器图标“排序和筛选数据集”(结果上方行左起第四个图标),并对一列或多列应用某些筛选器
  • 单击“脚本”或“脚本到文件”图标(顶行右侧的图标,它们看起来像小张纸)

这将为选定的表创建(有条件的)插入语句到活动窗口或文件。

Visual Studio 2013 的“筛选器”和“脚本”按钮

在此处输入图像描述

This can be done using Visual Studio too (at least in version 2013 onwards).

In VS 2013 it is also possible to filter the list of rows the inserts statement are based on, this is something not possible in SSMS as for as I know.

Perform the following steps:

  • Open the "SQL Server Object Explorer" window (menu: /View/SQL Server Object Explorer)
  • Open / expand the database and its tables
  • Right click on the table and choose "View data" from context menu
  • This will display the data in the main area
  • Optional step: Click on the filter icon "Sort and filter data set" (the fourth icon from the left on the row above the result) and apply some filter to one or more columns
  • Click on the "Script" or "Script to File" icons (the icons on the right of the top row, they look like little sheets of paper)

This will create the (conditional) insert statements for the selected table to the active window or file.

The "Filter" and "Script" buttons Visual Studio 2013:

enter image description here

葬花如无物 2024-07-30 06:50:43

正如 @Mike Ritacco 所提到的,但针对 SSMS 2008 R2 进行了更新

  1. 右键单击​​数据库名称
  2. 选择任务 > 生成脚本
  3. 根据您的设置,介绍页面可能会显示或不显示
  4. 选择“选择特定数据库对象”,
  5. 展开树视图并检查相关表格
  6. 单击“下一步”
  7. 单击“高级”
  8. 在“常规”部分下,为“要编写脚本的数据类型”选择适当的选项
  9. 完成向导

然后您将直接从 SSMS 中获取数据的所有 INSERT 语句。

编辑2016-10-25 SQL Server 2016/SSMS 13.0.15900.1

  1. 右键单击数据库名称

  2. 选择任务> 生成脚本

  3. 根据您的设置,介绍页面可能会显示或不显示

  4. 选择“选择特定数据库对象”,

  5. 展开树视图并检查相关表

  6. 单击“下一步”

  7. 单击“高级”

  8. 在“常规”部分下,为“要处理的数据类型”选择适当的选项
    脚本'

  9. 单击“确定”

  10. 选择是否要将输出发送至新查询、剪贴板或
    文件

  11. 单击“下一步”两次

  12. 您的脚本已根据您上面选择的设置准备就绪

  13. 单击“完成”

As mentioned by @Mike Ritacco but updated for SSMS 2008 R2

  1. Right click on the database name
  2. Choose Tasks > Generate scripts
  3. Depending on your settings the intro page may show or not
  4. Choose 'Select specific database objects',
  5. Expand the tree view and check the relevant tables
  6. Click Next
  7. Click Advanced
  8. Under General section, choose the appropriate option for 'Types of data to script'
  9. Complete the wizard

You will then get all of the INSERT statements for the data straight out of SSMS.

EDIT 2016-10-25 SQL Server 2016/SSMS 13.0.15900.1

  1. Right click on the database name

  2. Choose Tasks > Generate scripts

  3. Depending on your settings the intro page may show or not

  4. Choose 'Select specific database objects',

  5. Expand the tree view and check the relevant tables

  6. Click Next

  7. Click Advanced

  8. Under General section, choose the appropriate option for 'Types of data to
    script'

  9. Click OK

  10. Pick whether you want the output to go to a new query, the clipboard or a
    file

  11. Click Next twice

  12. Your script is prepared in accordance with the settings you picked above

  13. Click Finish

带刺的爱情 2024-07-30 06:50:43

您可以使用 SSMS 工具包(适用于 SQL Server 2005 和 2008)。 它具有生成插入语句的功能。

http://www.ssmstoolspack.com/

You can use SSMS Tools Pack (available for SQL Server 2005 and 2008). It comes with a feature for generating insert statements.

http://www.ssmstoolspack.com/

此刻的回忆 2024-07-30 06:50:43

我正在使用 SSMS 2008 版本 10.0.5500.0。 在此版本中,作为“生成脚本”向导的一部分,而不是“高级”按钮,而是出现以下屏幕。 在本例中,我只想插入数据而不需要创建语句,因此我必须更改两个圈出的属性Script Options

I'm using SSMS 2008 version 10.0.5500.0. In this version as part of the Generate Scripts wizard, instead of an Advanced button, there is the screen below. In this case, I wanted just the data inserted and no create statements, so I had to change the two circled propertiesScript Options

倥絔 2024-07-30 06:50:43

如果您需要编程访问,那么您可以使用开源存储过程“GenerateInsert”。

INSERT 语句生成器

作为一个简单快速的示例,生成 INSERT 语句表 AdventureWorks.Person.AddressType 执行以下语句:

USE [AdventureWorks];
GO
EXECUTE dbo.GenerateInsert @ObjectName = N'Person.AddressType';

这将生成以下脚本:

SET NOCOUNT ON
SET IDENTITY_INSERT Person.AddressType ON
INSERT INTO Person.AddressType
([AddressTypeID],[Name],[rowguid],[ModifiedDate])
VALUES
 (1,N'Billing','B84F78B1-4EFE-4A0E-8CB7-70E9F112F886',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(2,N'Home','41BC2FF6-F0FC-475F-8EB9-CEC0805AA0F2',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(3,N'Main Office','8EEEC28C-07A2-4FB9-AD0A-42D4A0BBC575',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(4,N'Primary','24CB3088-4345-47C4-86C5-17B535133D1E',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(5,N'Shipping','B29DA3F8-19A3-47DA-9DAA-15C84F4A83A5',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(6,N'Archive','A67F238A-5BA2-444B-966C-0467ED9C427F',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
SET IDENTITY_INSERT Person.AddressType OFF

If you need a programmatic access, then you can use an open source stored procedure `GenerateInsert.

INSERT statement(s) generator

Just as a simple and quick example, to generate INSERT statements for a table AdventureWorks.Person.AddressType execute following statements:

USE [AdventureWorks];
GO
EXECUTE dbo.GenerateInsert @ObjectName = N'Person.AddressType';

This will generate the following script:

SET NOCOUNT ON
SET IDENTITY_INSERT Person.AddressType ON
INSERT INTO Person.AddressType
([AddressTypeID],[Name],[rowguid],[ModifiedDate])
VALUES
 (1,N'Billing','B84F78B1-4EFE-4A0E-8CB7-70E9F112F886',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(2,N'Home','41BC2FF6-F0FC-475F-8EB9-CEC0805AA0F2',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(3,N'Main Office','8EEEC28C-07A2-4FB9-AD0A-42D4A0BBC575',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(4,N'Primary','24CB3088-4345-47C4-86C5-17B535133D1E',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(5,N'Shipping','B29DA3F8-19A3-47DA-9DAA-15C84F4A83A5',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
,(6,N'Archive','A67F238A-5BA2-444B-966C-0467ED9C427F',CONVERT(datetime,'2002-06-01 00:00:00.000',121))
SET IDENTITY_INSERT Person.AddressType OFF
冧九 2024-07-30 06:50:43

sp_generate_inserts 的第一个链接非常酷,这是一个非常简单的版本:

DECLARE @Fields VARCHAR(max); SET @Fields = '[QueueName], [iSort]' -- your fields, keep []
DECLARE @Table  VARCHAR(max); SET @Table  = 'Queues'               -- your table

DECLARE @SQL    VARCHAR(max)
SET @SQL = 'DECLARE @S VARCHAR(MAX)
SELECT @S = ISNULL(@S + '' UNION '', ''INSERT INTO ' + @Table + '(' + @Fields + ')'') + CHAR(13) + CHAR(10) + 
 ''SELECT '' + ' + REPLACE(REPLACE(REPLACE(@Fields, ',', ' + '', '' + '), '[', ''''''''' + CAST('),']',' AS VARCHAR(max)) + ''''''''') +' FROM ' + @Table + '
PRINT @S'

EXEC (@SQL)

在我的系统上,我得到以下结果:

INSERT INTO Queues([QueueName], [iSort])
SELECT 'WD: Auto Capture', '10' UNION 
SELECT 'Car/Lar', '11' UNION 
SELECT 'Scan Line', '21' UNION 
SELECT 'OCR', '22' UNION 
SELECT 'Dynamic Template', '23' UNION 
SELECT 'Fix MICR', '41' UNION 
SELECT 'Fix MICR (Supervisor)', '42' UNION 
SELECT 'Foreign MICR', '43' UNION 
...

The first link to sp_generate_inserts is pretty cool, here is a really simple version:

DECLARE @Fields VARCHAR(max); SET @Fields = '[QueueName], [iSort]' -- your fields, keep []
DECLARE @Table  VARCHAR(max); SET @Table  = 'Queues'               -- your table

DECLARE @SQL    VARCHAR(max)
SET @SQL = 'DECLARE @S VARCHAR(MAX)
SELECT @S = ISNULL(@S + '' UNION '', ''INSERT INTO ' + @Table + '(' + @Fields + ')'') + CHAR(13) + CHAR(10) + 
 ''SELECT '' + ' + REPLACE(REPLACE(REPLACE(@Fields, ',', ' + '', '' + '), '[', ''''''''' + CAST('),']',' AS VARCHAR(max)) + ''''''''') +' FROM ' + @Table + '
PRINT @S'

EXEC (@SQL)

On my system, I get this result:

INSERT INTO Queues([QueueName], [iSort])
SELECT 'WD: Auto Capture', '10' UNION 
SELECT 'Car/Lar', '11' UNION 
SELECT 'Scan Line', '21' UNION 
SELECT 'OCR', '22' UNION 
SELECT 'Dynamic Template', '23' UNION 
SELECT 'Fix MICR', '41' UNION 
SELECT 'Fix MICR (Supervisor)', '42' UNION 
SELECT 'Foreign MICR', '43' UNION 
...
伴我心暖 2024-07-30 06:50:43

我对这个问题的贡献是,Powershell INSERT 脚本生成器可以让您编写多个表的脚本,而无需使用繁琐的 SSMS GUI。 非常适合将“种子”数据快速持久保存到源代码控制中。

  1. 将以下脚本保存为“filename.ps1”。
  2. 对“CUSTOMIZE ME”下的区域进行自己的修改。
  3. 您可以按任意顺序将表列表添加到脚本中。
  4. 您可以在 Powershell ISE 中打开脚本并单击“播放”按钮,或者只需在 Powershell 命令提示符中执行脚本。

默认情况下,生成的 INSERT 脚本将是与该脚本位于同一文件夹下的“SeedData.sql”。

您将需要安装 SQL Server 管理对象程序集,如果您安装了 SSMS,则应该安装该程序集。

Add-Type -AssemblyName ("Microsoft.SqlServer.Smo, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")
Add-Type -AssemblyName ("Microsoft.SqlServer.ConnectionInfo, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")



#CUSTOMIZE ME
$outputFile = ".\SeedData.sql"
$connectionString = "Data Source=.;Initial Catalog=mydb;Integrated Security=True;"



$sqlConnection = new-object System.Data.SqlClient.SqlConnection($connectionString)
$conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection($sqlConnection)
$srv = new-object Microsoft.SqlServer.Management.Smo.Server($conn)
$db = $srv.Databases[$srv.ConnectionContext.DatabaseName]
$scr = New-Object Microsoft.SqlServer.Management.Smo.Scripter $srv
$scr.Options.FileName = $outputFile
$scr.Options.AppendToFile = $false
$scr.Options.ScriptSchema = $false
$scr.Options.ScriptData = $true
$scr.Options.NoCommandTerminator = $true

$tables = New-Object Microsoft.SqlServer.Management.Smo.UrnCollection



#CUSTOMIZE ME
$tables.Add($db.Tables["Category"].Urn)
$tables.Add($db.Tables["Product"].Urn)
$tables.Add($db.Tables["Vendor"].Urn)



[void]$scr.EnumScript($tables)

$sqlConnection.Close()

My contribution to the problem, a Powershell INSERT script generator that lets you script multiple tables without having to use the cumbersome SSMS GUI. Great for rapidly persisting "seed" data into source control.

  1. Save the below script as "filename.ps1".
  2. Make your own modifications to the areas under "CUSTOMIZE ME".
  3. You can add the list of tables to script in any order.
  4. You can open the script in Powershell ISE and hit the Play button, or simply execute the script in the Powershell command prompt.

By default, the INSERT script generated will be "SeedData.sql" under the same folder as the script.

You will need the SQL Server Management Objects assemblies installed, which should be there if you have SSMS installed.

Add-Type -AssemblyName ("Microsoft.SqlServer.Smo, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")
Add-Type -AssemblyName ("Microsoft.SqlServer.ConnectionInfo, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")



#CUSTOMIZE ME
$outputFile = ".\SeedData.sql"
$connectionString = "Data Source=.;Initial Catalog=mydb;Integrated Security=True;"



$sqlConnection = new-object System.Data.SqlClient.SqlConnection($connectionString)
$conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection($sqlConnection)
$srv = new-object Microsoft.SqlServer.Management.Smo.Server($conn)
$db = $srv.Databases[$srv.ConnectionContext.DatabaseName]
$scr = New-Object Microsoft.SqlServer.Management.Smo.Scripter $srv
$scr.Options.FileName = $outputFile
$scr.Options.AppendToFile = $false
$scr.Options.ScriptSchema = $false
$scr.Options.ScriptData = $true
$scr.Options.NoCommandTerminator = $true

$tables = New-Object Microsoft.SqlServer.Management.Smo.UrnCollection



#CUSTOMIZE ME
$tables.Add($db.Tables["Category"].Urn)
$tables.Add($db.Tables["Product"].Urn)
$tables.Add($db.Tables["Vendor"].Urn)



[void]$scr.EnumScript($tables)

$sqlConnection.Close()
音盲 2024-07-30 06:50:43

不要使用插入,请使用 BCP

Don't use inserts, use BCP

赴月观长安 2024-07-30 06:50:43

GenerateData 是一个很棒的工具。 由于源代码可供您使用,因此对其进行调整也非常容易。 一些不错的功能:

  • 人名和地点的名称生成器
  • 能够保存生成配置文件(下载并在本地设置后)
  • 能够通过脚本自定义和操作生成
  • 许多不同的输出(CSV、Javascript、JSON 等)数据(如果您需要在不同环境中测试该集并希望跳过数据库访问)
  • 免费。 但如果您发现该软件有用,请考虑捐赠:)。

GUI

GenerateData is an amazing tool for this. It's also very easy to make tweaks to it because the source code is available to you. A few nice features:

  • Name generator for peoples names and places
  • Ability to save Generation profile (after it is downloaded and set up locally)
  • Ability to customize and manipulate the generation through scripts
  • Many different outputs (CSV, Javascript, JSON, etc.) for the data (in case you need to test the set in different environments and want to skip the database access)
  • Free. But consider donating if you find the software useful :).

GUI

云淡月浅 2024-07-30 06:50:43

也许您可以尝试 SQL Server 发布向导
http://www.microsoft .com/downloads/details.aspx?FamilyId=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en

它有一个向导,可以帮助您编写插入语句的脚本。

Perhaps you can try the SQL Server Publishing Wizard
http://www.microsoft.com/downloads/details.aspx?FamilyId=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en

It has a wizard that helps you script insert statements.

西瓜 2024-07-30 06:50:43

为了获得带有过滤记录的 INSERT 语句(WHERE QUERY),您可以

  1. RIGHT CLICK TABLE SCRIPT TABLE AS > 创建到> 新查询

  2. 使用 TEMP_TABLE 重命名

  3. 现在运行

    从您的第一个表中选择 TEMP_TABLE,现在您的条件在这里

这样你的临时表将只包含你想要的记录,
现在,按照@Mike Ritacco的解释,通过仅使用数据运行脚本向导,您将获得准确的插入语句。

In order to get INSERT statement with filtered record(WHERE QUERY) you can

  1. RIGHT CLICK TABLE SCRIPT TABLE AS > CREATE TO > NEW QUERY

  2. RENAME IT WITH TEMP_TABLE

  3. NOW RUN

    SELECT INTO TEMP_TABLE FROM YOURFIRST TABLE WHERE NOW YOUR CRITERIA HERE

In this way you temp table will have only the record that you want ,
Now by running script wizard as explained by @Mike Ritacco with DATA ONLY you will get the exact insert statements.

心房的律动 2024-07-30 06:50:43

我使用 sqlite 来做到这一点。 我发现它对于创建临时/测试数据库非常非常有用。

sqlite3 foo.sqlite .dump > > foo_as_a_bunch_of_inserts.sql

I use sqlite to do this. I find it very, very useful for creating scratch/test databases.

sqlite3 foo.sqlite .dump > foo_as_a_bunch_of_inserts.sql

烟燃烟灭 2024-07-30 06:50:43

您可以使用我几年前编写的这个简单且免费的应用程序生成INSERTMERGE语句:
数据脚本编写器(Windows 桌面应用程序)

在此处输入图像描述
另外,我最近写了一篇关于这些工具的博客文章以及利用 SSDT 来部署包含数据的数据库的方法。 了解更多:
编写脚本并部署数据库数据SSDT项目

You can generate INSERT or MERGE statement with this simple and free application I wrote a few years ago:
Data Script Writer (Desktop Application for Windows)

enter image description here
Also, I wrote a blog post about these tools recently and approach to leveraging SSDT for a deployment database with data. Find out more:
Script and deploy the data for database from SSDT project

风吹雨成花 2024-07-30 06:50:43

我制作了一个简单易用的实用程序,希望您喜欢。

  • 它不需要在数据库上创建任何对象(易于在生产环境中使用)。
  • 您不需要安装任何东西。 这只是一个常规脚本。
  • 您不需要特殊权限。 只需定期读取访问就足够了。
  • 让您复制表的所有行,或指定 WHERE 条件,以便仅生成您想要的行。
  • 让您指定单个或多个表以及要生成的不同条件语句。

如果生成的 INSERT 语句被截断,请检查 Management Studio 选项中结果的限制文本长度: Tools > 选项查询结果> SQL服务器> 结果到网格,“检索到的最大字符数”下的“非 XML 数据”值。

    -- Make sure you're on the correct database
    SET NOCOUNT ON;
    BEGIN TRY
    BEGIN TRANSACTION

    DECLARE @Tables TABLE (
        TableName          varchar(50) NOT NULL,
        Arguments           varchar(1000) NULL
    );

    -- INSERT HERE THE TABLES AND CONDITIONS YOU WANT TO GENERATE THE INSERT STATEMENTS
    INSERT INTO @Tables (TableName, Arguments) VALUES ('table1', 'WHERE field1 = 3101928464');
    -- (ADD MORE LINES IF YOU LIKE) INSERT INTO @Tables (TableName, Arguments) VALUES ('table2', 'WHERE field2 IN (1, 3, 5)');


    -- YOU DON'T NEED TO EDIT FROM NOW ON.
    -- Generating the Script
    DECLARE @TableName  varchar(50),
            @Arguments  varchar(1000),
            @ColumnName varchar(50),
            @strSQL     varchar(max),
            @strSQL2    varchar(max),
            @Lap        int,
            @Iden       int,
            @TypeOfData int;

    DECLARE C1 CURSOR FOR
    SELECT TableName, Arguments FROM @Tables
    OPEN C1
    FETCH NEXT FROM C1 INTO @TableName, @Arguments;
    WHILE @@FETCH_STATUS = 0
    BEGIN

        -- If you want to delete the lines before inserting, uncomment the next line
        -- PRINT 'DELETE FROM ' + @TableName + ' ' + @Arguments

        SET @strSQL = 'INSERT INTO ' + @TableName + ' (';

        -- List all the columns from the table (to the INSERT into columns...)
        SET @Lap = 0;
        DECLARE C2 CURSOR FOR
        SELECT sc.name, sc.type FROM syscolumns sc INNER JOIN sysobjects so ON so.id = sc.id AND so.name = @TableName AND so.type = 'U' WHERE sc.colstat = 0 ORDER BY sc.colorder
        OPEN C2
        FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
        WHILE @@FETCH_STATUS = 0
        BEGIN
            IF(@Lap>0)
            BEGIN
                SET @strSQL = @strSQL + ', ';
            END

            SET @strSQL = @strSQL + '[' + @ColumnName + ']';
            SET @Lap = @Lap + 1;
            FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
        END
        CLOSE C2
        DEALLOCATE C2

        SET @strSQL = @strSQL + ')'
        SET @strSQL2 = 'SELECT ''' + @strSQL + '
SELECT '' + ';

        -- List all the columns from the table again (for the SELECT that will be the input to the INSERT INTO statement)
        SET @Lap = 0;
        DECLARE C2 CURSOR FOR
        SELECT sc.name, sc.type FROM syscolumns sc INNER JOIN sysobjects so ON so.id = sc.id AND so.name = @TableName AND so.type = 'U' WHERE sc.colstat = 0 ORDER BY sc.colorder
        OPEN C2
        FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
        WHILE @@FETCH_STATUS = 0
        BEGIN
            IF(@Lap>0)
            BEGIN
                SET @strSQL2 = @strSQL2 + ' + '', '' + ';
            END

            -- For each data type, convert the data properly
            IF(@TypeOfData IN (55, 106, 56, 108, 63, 38, 109, 50, 48, 52)) -- Numbers
                SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), ' + @ColumnName + '), ''NULL'') + '' as ' + @ColumnName + '''';
            ELSE IF(@TypeOfData IN (60, 62)) -- Float Numbers
                SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), CONVERT(decimal(18,5), ' + @ColumnName + ')), ''NULL'') + '' as ' + @ColumnName + '''';
            ELSE IF(@TypeOfData IN (61, 111)) -- Datetime
                SET @strSQL2 = @strSQL2 + 'ISNULL( '''''''' + CONVERT(varchar(max),' + @ColumnName + ', 121) + '''''''', ''NULL'') + '' as ' + @ColumnName + '''';
            ELSE IF(@TypeOfData IN (37, 47, 39, 0, 110)) -- Texts
                SET @strSQL2 = @strSQL2 + 'ISNULL('''''''' + RTRIM(LTRIM(' + @ColumnName + ')) + '''''''', ''NULL'') + '' as ' + @ColumnName + '''';
            ELSE -- Unknown data types
                SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), ' + @ColumnName + '), ''NULL'') + '' as ' + @ColumnName + '(INCORRECT TYPE ' + CONVERT(varchar(10), @TypeOfData) + ')''';

            SET @Lap = @Lap + 1;
            FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
        END
        CLOSE C2
        DEALLOCATE C2

        SET @strSQL2 = @strSQL2 + ' as [-- ' + @TableName + ']
FROM ' + @TableName + ' WITH (NOLOCK) ' + @Arguments

        SET @strSQL2 = @strSQL2 + ';
';
        --PRINT @strSQL;
        --PRINT @strSQL2;
        EXEC(@strSQL2);

        FETCH NEXT FROM C1 INTO @TableName, @Arguments;
    END
    CLOSE C1
    DEALLOCATE C1

    ROLLBACK
END TRY
BEGIN CATCH
    ROLLBACK TRAN
    SELECT 0 AS Situacao;
    SELECT
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage,
        @strSQL As strSQL,
        @strSQL2 as strSQL2;
END CATCH

I made a simple to use utility, hope you enjoy.

  • It doesn't need to create any objects on the database (easy to use on production environment).
  • You don't need to install anything. It's just a regular script.
  • You don't need special permissions. Just regular read access is enough.
  • Let you copy all the lines of a table, or specify WHERE conditions so only the lines you want will be generated.
  • Let you specify a single or multiple tables and different condition statements to be generated.

If the generated INSERT statements are being truncated, check the limit text length of the results on the Management Studio Options: Tools > Options, Query Results > SQL Server > Results to Grid, "Non XML data" value under "Maximum Characters Retrieved".

    -- Make sure you're on the correct database
    SET NOCOUNT ON;
    BEGIN TRY
    BEGIN TRANSACTION

    DECLARE @Tables TABLE (
        TableName          varchar(50) NOT NULL,
        Arguments           varchar(1000) NULL
    );

    -- INSERT HERE THE TABLES AND CONDITIONS YOU WANT TO GENERATE THE INSERT STATEMENTS
    INSERT INTO @Tables (TableName, Arguments) VALUES ('table1', 'WHERE field1 = 3101928464');
    -- (ADD MORE LINES IF YOU LIKE) INSERT INTO @Tables (TableName, Arguments) VALUES ('table2', 'WHERE field2 IN (1, 3, 5)');


    -- YOU DON'T NEED TO EDIT FROM NOW ON.
    -- Generating the Script
    DECLARE @TableName  varchar(50),
            @Arguments  varchar(1000),
            @ColumnName varchar(50),
            @strSQL     varchar(max),
            @strSQL2    varchar(max),
            @Lap        int,
            @Iden       int,
            @TypeOfData int;

    DECLARE C1 CURSOR FOR
    SELECT TableName, Arguments FROM @Tables
    OPEN C1
    FETCH NEXT FROM C1 INTO @TableName, @Arguments;
    WHILE @@FETCH_STATUS = 0
    BEGIN

        -- If you want to delete the lines before inserting, uncomment the next line
        -- PRINT 'DELETE FROM ' + @TableName + ' ' + @Arguments

        SET @strSQL = 'INSERT INTO ' + @TableName + ' (';

        -- List all the columns from the table (to the INSERT into columns...)
        SET @Lap = 0;
        DECLARE C2 CURSOR FOR
        SELECT sc.name, sc.type FROM syscolumns sc INNER JOIN sysobjects so ON so.id = sc.id AND so.name = @TableName AND so.type = 'U' WHERE sc.colstat = 0 ORDER BY sc.colorder
        OPEN C2
        FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
        WHILE @@FETCH_STATUS = 0
        BEGIN
            IF(@Lap>0)
            BEGIN
                SET @strSQL = @strSQL + ', ';
            END

            SET @strSQL = @strSQL + '[' + @ColumnName + ']';
            SET @Lap = @Lap + 1;
            FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
        END
        CLOSE C2
        DEALLOCATE C2

        SET @strSQL = @strSQL + ')'
        SET @strSQL2 = 'SELECT ''' + @strSQL + '
SELECT '' + ';

        -- List all the columns from the table again (for the SELECT that will be the input to the INSERT INTO statement)
        SET @Lap = 0;
        DECLARE C2 CURSOR FOR
        SELECT sc.name, sc.type FROM syscolumns sc INNER JOIN sysobjects so ON so.id = sc.id AND so.name = @TableName AND so.type = 'U' WHERE sc.colstat = 0 ORDER BY sc.colorder
        OPEN C2
        FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
        WHILE @@FETCH_STATUS = 0
        BEGIN
            IF(@Lap>0)
            BEGIN
                SET @strSQL2 = @strSQL2 + ' + '', '' + ';
            END

            -- For each data type, convert the data properly
            IF(@TypeOfData IN (55, 106, 56, 108, 63, 38, 109, 50, 48, 52)) -- Numbers
                SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), ' + @ColumnName + '), ''NULL'') + '' as ' + @ColumnName + '''';
            ELSE IF(@TypeOfData IN (60, 62)) -- Float Numbers
                SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), CONVERT(decimal(18,5), ' + @ColumnName + ')), ''NULL'') + '' as ' + @ColumnName + '''';
            ELSE IF(@TypeOfData IN (61, 111)) -- Datetime
                SET @strSQL2 = @strSQL2 + 'ISNULL( '''''''' + CONVERT(varchar(max),' + @ColumnName + ', 121) + '''''''', ''NULL'') + '' as ' + @ColumnName + '''';
            ELSE IF(@TypeOfData IN (37, 47, 39, 0, 110)) -- Texts
                SET @strSQL2 = @strSQL2 + 'ISNULL('''''''' + RTRIM(LTRIM(' + @ColumnName + ')) + '''''''', ''NULL'') + '' as ' + @ColumnName + '''';
            ELSE -- Unknown data types
                SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), ' + @ColumnName + '), ''NULL'') + '' as ' + @ColumnName + '(INCORRECT TYPE ' + CONVERT(varchar(10), @TypeOfData) + ')''';

            SET @Lap = @Lap + 1;
            FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
        END
        CLOSE C2
        DEALLOCATE C2

        SET @strSQL2 = @strSQL2 + ' as [-- ' + @TableName + ']
FROM ' + @TableName + ' WITH (NOLOCK) ' + @Arguments

        SET @strSQL2 = @strSQL2 + ';
';
        --PRINT @strSQL;
        --PRINT @strSQL2;
        EXEC(@strSQL2);

        FETCH NEXT FROM C1 INTO @TableName, @Arguments;
    END
    CLOSE C1
    DEALLOCATE C1

    ROLLBACK
END TRY
BEGIN CATCH
    ROLLBACK TRAN
    SELECT 0 AS Situacao;
    SELECT
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage,
        @strSQL As strSQL,
        @strSQL2 as strSQL2;
END CATCH
相思故 2024-07-30 06:50:43

上面有许多用于生成插入语句的好脚本,但我尝试了自己的一个脚本,以使其尽可能用户友好,并且还能够执行 UPDATE 语句。 + 将结果打包为可按日期存储的 .sql 文件。

它将带有 WHERE 子句的普通 SELECT 语句作为输入,然后输出 Insert 语句和 update 语句的列表。 它们一起形成一种 IF NOT EXISTS () INSERT ELSE UPDATE 当存在需要从最终 INSERT/UPDATE 语句中排除的不可更新列时,它也很方便。

下面的脚本可以做的另一件事是:它甚至可以处理与其他表的 INNER JOIN 作为存储过程的输入语句。 它可以作为一个穷人的发布管理工具,在您整天键入 sql SELECT 语句时触手可及。

原始帖子:在 SQL Server 中生成 UPDATE 语句具体表格

CREATE PROCEDURE [dbo].[sp_generate_updates] (
    @fullquery              nvarchar(max) = '',
    @ignore_field_input     nvarchar(MAX) = '',
    @PK_COLUMN_NAME         nvarchar(MAX) = ''
)
AS

SET NOCOUNT ON
SET QUOTED_IDENTIFIER ON
/*
-- For Standard USAGE: (where clause is mandatory)
                EXEC [sp_generate_updates] 'select * from dbo.mytable where mytext=''1''  ' 
        OR
                SET QUOTED_IDENTIFIER OFF 
                EXEC [sp_generate_updates] "select * from dbo.mytable where mytext='1'    "

-- For ignoring specific columns  (to ignore in the UPDATE and INSERT SQL statement) 
                EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1  ' , 'Column01,Column02'

-- For just updates without insert statement (replace the * )
                EXEC [sp_generate_updates] 'select Column01, Column02 from dbo.mytable where 1=1  ' 

-- For tables without a primary key: construct the key in the third variable
                EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1  '  ,'','your_chosen_primary_key_Col1,key_Col2'

-- For complex updates with JOINED tables 
                EXEC [sp_generate_updates] 'select o1.Name,  o1.category, o2.name+ '_hello_world' as #name 
                                            from overnightsetting o1 
                                            inner join overnightsetting o2  on o1.name=o2.name  
                                            where o1.name like '%appserver%' 
                (REMARK about above:   the use of # in front of a column name (so #abc) can do an update of that columname (abc) with any column from an inner joined table where you use the alias #abc )


-------------README for the deeper interested person:
            Goal of the Stored PROCEDURE is to get updates from simple SQL SELECT statements. It is made ot be simple but fast and powerfull. As always => power is nothing without control, so check before you execute.
            Its power sits also in the fact that you can make insert statements, so combined gives you a  "IF NOT EXISTS()  INSERT "   capability. 

            The scripts work were there are primary keys or identity columns on table you want to update (/ or make inserts for).
            It will also works when no primary keys / identity column exist(s) and you define them yourselve. But then be carefull (duplicate hits can occur). When the table has a primary key it will always be used.
            The script works with a real  temporary table, made on the fly   (APPROPRIATE RIGHTS needed), to put the values inside from the script, then add 3 columns for constructing the "insert into tableX (...) values ()" ,  and the 2 update statement.
            We work with temporary structures like   "where columnname = {Columnname}" and then later do the update on that temptable for the columns values found on that same line.
                    example  "where columnname = {Columnname}"  for birthdate becomes   "where birthdate = {birthdate}" an then we find the birthdate value on that line inside the temp table.
            So then the statement becomes  "where birthdate = {19800417}"
            Enjoy releasing scripts as of now...                                        by  Pieter van Nederkassel  - freeware "CC BY-SA" (+use at own risk)
*/
IF OBJECT_ID('tempdb..#ignore','U') IS NOT NULL     DROP TABLE #ignore
DECLARE @stringsplit_table               TABLE (col nvarchar(255), dtype  nvarchar(255)) -- table to store the primary keys or identity key
DECLARE @PK_condition                    nvarchar(512), -- placeholder for WHERE pk_field1 = pk_value1 AND pk_field2 = pk_value2 AND ...
        @pkstring                        NVARCHAR(512),  -- sting to store the primary keys or the idendity key
        @table_name                      nvarchar(512), -- (left) table name, including schema
        @table_N_where_clause            nvarchar(max), -- tablename 
        @table_alias                     nvarchar(512), -- holds the (left) table alias if one available, else @table_name
        @table_schema                    NVARCHAR(30),  -- schema of @table_name
        @update_list1                    NVARCHAR(MAX), -- placeholder for SET fields section of update
        @update_list2                    NVARCHAR(MAX), -- placeholder for SET fields section of update value comming from other tables in the join, other than the main table to update => updateof base table possible with inner join
        @list_all_cols                   BIT = 0,       -- placeholder for values for the insert into table VALUES command
        @select_list                     NVARCHAR(MAX), -- placeholder for SELECT fields of (left) table
        @COLUMN_NAME                     NVARCHAR(255), -- will hold column names of the (left) table
        @sql                             NVARCHAR(MAX), -- sql statement variable
        @getdate                         NVARCHAR(17),  -- transform getdate() to YYYYMMDDHHMMSSMMM
        @tmp_table                       NVARCHAR(255), -- will hold the name of a physical temp table
        @pk_separator                    NVARCHAR(1),   -- separator used in @PK_COLUMN_NAME if provided (only checking obvious ones ,;|-)
        @COLUMN_NAME_DATA_TYPE           NVARCHAR(100), -- needed for insert statements to convert to right text string
        @own_pk                          BIT = 0        -- check if table has PK (0) or if provided PK will be used (1)




set @ignore_field_input=replace(replace(replace(@ignore_field_input,' ',''),'[',''),']','')
set @PK_COLUMN_NAME=    replace(replace(replace(@PK_COLUMN_NAME,    ' ',''),'[',''),']','')

-- first we remove all linefeeds from the user query
set @fullquery=replace(replace(replace(@fullquery,char(10),''),char(13),' '),'  ',' ')
set @table_N_where_clause=@fullquery
if charindex ('order by' , @table_N_where_clause) > 0
    print ' WARNING:        ORDER BY NOT ALLOWED IN UPDATE ...'
if @PK_COLUMN_NAME <> ''
    select ' WARNING:        IF you select your own primary keys, make double sure before doing the update statements below!! '
--print @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) = 0
    set @table_N_where_clause= 'select * from ' + @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) > 0
    exec (@table_N_where_clause)

set @table_N_where_clause=rtrim(ltrim(substring(@table_N_where_clause,CHARINDEX(' from ', @table_N_where_clause )+6, 4000)))
--print @table_N_where_clause 
set @table_name=left(@table_N_where_clause,CHARINDEX(' ', @table_N_where_clause )-1)


IF CHARINDEX('where ', @table_N_where_clause) > 0             SELECT @table_alias = LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(@table_N_where_clause,1, CHARINDEX('where ', @table_N_where_clause )-1),'(nolock)',''),@table_name,'')))
IF CHARINDEX('join ',  @table_alias) > 0                      SELECT @table_alias = SUBSTRING(@table_alias, 1, CHARINDEX(' ', @table_alias)-1) -- until next space
IF LEN(@table_alias) = 0                                      SELECT @table_alias = @table_name
IF (charindex (' *' , @fullquery) > 0 or charindex (@table_alias+'.*' , @fullquery) > 0 )     set @list_all_cols=1
/*       
       print @fullquery     
       print @table_alias
       print @table_N_where_clause
       print @table_name
*/


-- Prepare PK condition
        SELECT @table_schema = CASE WHEN CHARINDEX('.',@table_name) > 0 THEN LEFT(@table_name, CHARINDEX('.',@table_name)-1) ELSE 'dbo' END

        SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
        WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
        AND TABLE_SCHEMA = @table_schema

        SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
        WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
        AND i1.TABLE_SCHEMA = @table_schema

            -- if no primary keys exist then we try for identity columns
                IF @PK_condition is null SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
                FROM  INFORMATION_SCHEMA.COLUMNS
                WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 
                AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
                AND TABLE_SCHEMA = @table_schema

                IF @pkstring is null SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
                FROM  INFORMATION_SCHEMA.COLUMNS
                WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 
                AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
                AND TABLE_SCHEMA = @table_schema
-- Same but in form of a table

        INSERT INTO @stringsplit_table
        SELECT 'pk_'+i1.COLUMN_NAME as col, i2.DATA_TYPE as dtype
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
        inner join INFORMATION_SCHEMA.COLUMNS i2
        on  i1.TABLE_NAME = i2.TABLE_NAME AND i1.TABLE_SCHEMA =  i2.TABLE_SCHEMA
        WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
        AND i1.TABLE_SCHEMA = @table_schema

                -- if no primary keys exist then we try for identity columns
                IF 0=(select count(*) from @stringsplit_table) INSERT INTO @stringsplit_table
                SELECT 'pk_'+i2.COLUMN_NAME as col, i2.DATA_TYPE as dtype
                FROM INFORMATION_SCHEMA.COLUMNS i2
                WHERE COLUMNPROPERTY(object_id(i2.TABLE_SCHEMA+'.'+i2.TABLE_NAME), i2.COLUMN_NAME, 'IsIdentity') = 1 
                AND i2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
                AND i2.TABLE_SCHEMA = @table_schema

-- NOW handling the primary key given as parameter to the main batch

SELECT @pk_separator = ',' -- take this as default, we'll check lower if it's a different one
IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME <> ''
BEGIN
    IF CHARINDEX(';', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = ';'
    ELSE IF CHARINDEX('|', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = '|'
    ELSE IF CHARINDEX('-', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = '-'

    SELECT @PK_condition = NULL -- make sure to make it NULL, in case it was ''
    INSERT INTO @stringsplit_table
    SELECT LTRIM(RTRIM(x.value)) , 'datetime'  FROM STRING_SPLIT(@PK_COLUMN_NAME, @pk_separator) x  
    SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME(x.col) + ' = ' + replace(QUOTENAME(x.col,'{'),'{','{pk_')
      FROM @stringsplit_table x

    SELECT @PK_COLUMN_NAME = NULL -- make sure to make it NULL, in case it was ''
    SELECT @PK_COLUMN_NAME = ISNULL(@PK_COLUMN_NAME + ', ', '') + QUOTENAME(x.col) + ' as pk_' + x.col
      FROM @stringsplit_table x
    --print 'pkcolumns  '+ isnull(@PK_COLUMN_NAME,'')
    update @stringsplit_table set col='pk_' + col
    SELECT @own_pk = 1
END
ELSE IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME = ''
BEGIN
    RAISERROR('No Primary key or Identity column available on table. Add some columns as the third parameter when calling this SP to make your own temporary PK., also remove  [] from tablename',17,1)
END


-- IF there are no primary keys or an identity key in the table active, then use the given columns as a primary key


if isnull(@pkstring,'')   = ''  set    @pkstring  = @PK_COLUMN_NAME
IF ISNULL(@pkstring, '') <> ''  SELECT @fullquery = REPLACE(@fullquery, 'SELECT ','SELECT ' + @pkstring + ',' )
--print @pkstring




-- ignore fields for UPDATE STATEMENT (not ignored for the insert statement,  in iserts statement we ignore only identity Columns and the columns provided with the main stored proc )
-- Place here all fields that you know can not be converted to nvarchar() values correctly, an thus should not be scripted for updates)
-- for insert we will take these fields along, although they will be incorrectly represented!!!!!!!!!!!!!.
SELECT           ignore_field = 'uniqueidXXXX' INTO #ignore 
UNION ALL SELECT ignore_field = 'UPDATEMASKXXXX'
UNION ALL SELECT ignore_field = 'UIDXXXXX'
UNION ALL SELECT value FROM  string_split(@ignore_field_input,@pk_separator)




SELECT @getdate = REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(30), GETDATE(), 121), '-', ''), ' ', ''), ':', ''), '.', '')
SELECT @tmp_table = 'Release_DATA__' + @getdate + '__' + REPLACE(@table_name,@table_schema+'.','') 

SET @sql = replace( @fullquery,  ' from ',  ' INTO ' + @tmp_table +' from ')
----print (@sql)
exec (@sql)



SELECT @sql = N'alter table ' + @tmp_table + N'  add update_stmt1  nvarchar(max), update_stmt2 nvarchar(max) , update_stmt3 nvarchar(max)'
EXEC (@sql)

-- Prepare update field list (only columns from the temp table are taken if they also exist in the base table to update)
SELECT @update_list1 = ISNULL(@update_list1 + ', ', '') + 
                      CASE WHEN C1.COLUMN_NAME = 'ModifiedBy' THEN '[ModifiedBy] = left(right(replace(CONVERT(VARCHAR(19),[Modified],121),''''-'''',''''''''),19) +''''-''''+right(SUSER_NAME(),30),50)'
                           WHEN C1.COLUMN_NAME = 'Modified' THEN '[Modified] = GETDATE()'
                           ELSE QUOTENAME(C1.COLUMN_NAME) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
                      END
FROM INFORMATION_SCHEMA.COLUMNS c1
inner join INFORMATION_SCHEMA.COLUMNS c2
on c1.COLUMN_NAME =c2.COLUMN_NAME and c2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')  AND c2.TABLE_SCHEMA = @table_schema
WHERE c1.TABLE_NAME = @tmp_table --REPLACE(@table_name,@table_schema+'.','') 
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND COLUMNPROPERTY(object_id(c2.TABLE_SCHEMA+'.'+c2.TABLE_NAME), c2.COLUMN_NAME, 'IsIdentity') <> 1
AND NOT EXISTS (SELECT 1 
                  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku 
                 WHERE 1 = 1
                   AND ku.TABLE_NAME = c2.TABLE_NAME
                   AND ku.TABLE_SCHEMA = c2.TABLE_SCHEMA
                   AND ku.COLUMN_NAME = c2.COLUMN_NAME
                   AND OBJECTPROPERTY(OBJECT_ID(ku.CONSTRAINT_SCHEMA + '.' + QUOTENAME(ku.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1)
AND NOT EXISTS (SELECT 1 FROM @stringsplit_table x WHERE x.col = c2.COLUMN_NAME AND @own_pk = 1)

-- Prepare update field list  (here we only take columns that commence with a #, as this is our queue for doing the update that comes from an inner joined table)
SELECT @update_list2 = ISNULL(@update_list2 + ', ', '') +  QUOTENAME(replace( C1.COLUMN_NAME,'#','')) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
FROM INFORMATION_SCHEMA.COLUMNS c1
WHERE c1.TABLE_NAME = @tmp_table --AND c1.TABLE_SCHEMA = @table_schema
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND c1.COLUMN_NAME like '#%'

-- similar for select list, but take all fields
SELECT @select_list = ISNULL(@select_list + ', ', '') + QUOTENAME(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
AND TABLE_SCHEMA = @table_schema
AND COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') <> 1  -- Identity columns are filled automatically by MSSQL, not needed at Insert statement
AND QUOTENAME(c.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here


SELECT @PK_condition = REPLACE(@PK_condition, '[pk_', '[')
set @select_list='if not exists (select * from '+  REPLACE(@table_name,@table_schema+'.','') +'  where '+  @PK_condition +')  INSERT INTO '+ REPLACE(@table_name,@table_schema+'.','')   + '('+ @select_list  + ') VALUES (' + replace(replace(@select_list,'[','{'),']','}') + ')'
SELECT @sql = N'UPDATE ' + @tmp_table + ' set update_stmt1 = ''' + @select_list + '''' 
if @list_all_cols=1 EXEC (@sql)



--print 'select==========  ' + @select_list
--print 'update==========  ' + @update_list1


SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt2 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name + 
                                          N' SET ' + @update_list1 + N''' + ''' +
                                          N' WHERE ' + @PK_condition + N''') ' 

EXEC (@sql)
--print @sql



SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt3 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name + 
                                          N' SET ' + @update_list2 + N''' + ''' +
                                          N' WHERE ' + @PK_condition + N''') ' 

EXEC (@sql)
--print @sql


-- LOOPING OVER ALL base tables column for the INSERT INTO .... VALUES
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
    SELECT COLUMN_NAME, DATA_TYPE
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME = (CASE WHEN @list_all_cols=0 THEN @tmp_table ELSE REPLACE(@table_name,@table_schema+'.','') END )
    AND TABLE_SCHEMA = @table_schema
        UNION--pned
    SELECT col, 'datetime' FROM @stringsplit_table

OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @sql = 
    CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
    ELSE  
                  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
    END
    ----PRINT @sql
    EXEC (@sql)
    FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns

--SELECT col FROM @stringsplit_table -- these are the primary keys

-- LOOPING OVER ALL temp tables column for the Update values
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
    SELECT COLUMN_NAME,DATA_TYPE
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME =  @tmp_table --    AND TABLE_SCHEMA = @table_schema
       UNION--pned
    SELECT col, 'datetime' FROM @stringsplit_table

OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @sql = 
    CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL''))  ' 
    ELSE    
                  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
    END
    EXEC (@sql)
    ----print @sql
    FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns

SET @sql = 'Select * from  ' + @tmp_table + ';'
--exec (@sql)

SELECT @sql = N'
IF OBJECT_ID(''' + @tmp_table + N''', ''U'') IS NOT NULL
BEGIN
       SELECT   ''USE ' + DB_NAME()  + '''  as executelist 
              UNION ALL
       SELECT   ''GO ''  as executelist 
              UNION ALL
       SELECT   '' /*PRESCRIPT CHECK  */              ' + replace(@fullquery,'''','''''')+''' as executelist 
              UNION ALL
       SELECT update_stmt1 as executelist FROM ' + @tmp_table + N' where update_stmt1 is not null
              UNION ALL
       SELECT update_stmt2 as executelist FROM ' + @tmp_table + N' where update_stmt2 is not null
              UNION ALL
       SELECT isnull(update_stmt3, '' add more columns inn query please'')  as executelist FROM ' + @tmp_table + N' where update_stmt3 is not null
              UNION ALL
       SELECT ''--EXEC usp_AddInstalledScript 5, 5, 1, 1, 1, ''''' + @tmp_table + '.sql'''', 2 ''  as executelist
              UNION ALL 
       SELECT   '' /*VERIFY WITH:  */              ' + replace(@fullquery,'''','''''')+''' as executelist 
              UNION ALL
       SELECT ''-- SCRIPT LOCATION:      F:\CopyPaste\++Distributionpoint++\Release_Management\' + @tmp_table + '.sql''  as executelist   
END'
exec (@sql)

SET @sql = 'DROP TABLE ' + @tmp_table + ';'
exec (@sql)

There are many good scripts above for generating insert statements, but I attempted one of my own to make it as user friendly as possible and to also be able to do UPDATE statements. + package the result ready for .sql files that can be stored by date.

It takes as input your normal SELECT statement with WHERE clause, then outputs a list of Insert statements and update statements. Together they form a sort of IF NOT EXISTS () INSERT ELSE UPDATE It is handy too when there are non-updatable columns that need exclusion from the final INSERT/UPDATE statement.

Another thing that below script can do is: it can even handle INNER JOINs with other tables as input statement for the stored proc. It can be handy as a poor man's Release management tool that sits right at your finger tips where you are typing the sql SELECT statements all day.

original post : Generate UPDATE statement in SQL Server for specific table

CREATE PROCEDURE [dbo].[sp_generate_updates] (
    @fullquery              nvarchar(max) = '',
    @ignore_field_input     nvarchar(MAX) = '',
    @PK_COLUMN_NAME         nvarchar(MAX) = ''
)
AS

SET NOCOUNT ON
SET QUOTED_IDENTIFIER ON
/*
-- For Standard USAGE: (where clause is mandatory)
                EXEC [sp_generate_updates] 'select * from dbo.mytable where mytext=''1''  ' 
        OR
                SET QUOTED_IDENTIFIER OFF 
                EXEC [sp_generate_updates] "select * from dbo.mytable where mytext='1'    "

-- For ignoring specific columns  (to ignore in the UPDATE and INSERT SQL statement) 
                EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1  ' , 'Column01,Column02'

-- For just updates without insert statement (replace the * )
                EXEC [sp_generate_updates] 'select Column01, Column02 from dbo.mytable where 1=1  ' 

-- For tables without a primary key: construct the key in the third variable
                EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1  '  ,'','your_chosen_primary_key_Col1,key_Col2'

-- For complex updates with JOINED tables 
                EXEC [sp_generate_updates] 'select o1.Name,  o1.category, o2.name+ '_hello_world' as #name 
                                            from overnightsetting o1 
                                            inner join overnightsetting o2  on o1.name=o2.name  
                                            where o1.name like '%appserver%' 
                (REMARK about above:   the use of # in front of a column name (so #abc) can do an update of that columname (abc) with any column from an inner joined table where you use the alias #abc )


-------------README for the deeper interested person:
            Goal of the Stored PROCEDURE is to get updates from simple SQL SELECT statements. It is made ot be simple but fast and powerfull. As always => power is nothing without control, so check before you execute.
            Its power sits also in the fact that you can make insert statements, so combined gives you a  "IF NOT EXISTS()  INSERT "   capability. 

            The scripts work were there are primary keys or identity columns on table you want to update (/ or make inserts for).
            It will also works when no primary keys / identity column exist(s) and you define them yourselve. But then be carefull (duplicate hits can occur). When the table has a primary key it will always be used.
            The script works with a real  temporary table, made on the fly   (APPROPRIATE RIGHTS needed), to put the values inside from the script, then add 3 columns for constructing the "insert into tableX (...) values ()" ,  and the 2 update statement.
            We work with temporary structures like   "where columnname = {Columnname}" and then later do the update on that temptable for the columns values found on that same line.
                    example  "where columnname = {Columnname}"  for birthdate becomes   "where birthdate = {birthdate}" an then we find the birthdate value on that line inside the temp table.
            So then the statement becomes  "where birthdate = {19800417}"
            Enjoy releasing scripts as of now...                                        by  Pieter van Nederkassel  - freeware "CC BY-SA" (+use at own risk)
*/
IF OBJECT_ID('tempdb..#ignore','U') IS NOT NULL     DROP TABLE #ignore
DECLARE @stringsplit_table               TABLE (col nvarchar(255), dtype  nvarchar(255)) -- table to store the primary keys or identity key
DECLARE @PK_condition                    nvarchar(512), -- placeholder for WHERE pk_field1 = pk_value1 AND pk_field2 = pk_value2 AND ...
        @pkstring                        NVARCHAR(512),  -- sting to store the primary keys or the idendity key
        @table_name                      nvarchar(512), -- (left) table name, including schema
        @table_N_where_clause            nvarchar(max), -- tablename 
        @table_alias                     nvarchar(512), -- holds the (left) table alias if one available, else @table_name
        @table_schema                    NVARCHAR(30),  -- schema of @table_name
        @update_list1                    NVARCHAR(MAX), -- placeholder for SET fields section of update
        @update_list2                    NVARCHAR(MAX), -- placeholder for SET fields section of update value comming from other tables in the join, other than the main table to update => updateof base table possible with inner join
        @list_all_cols                   BIT = 0,       -- placeholder for values for the insert into table VALUES command
        @select_list                     NVARCHAR(MAX), -- placeholder for SELECT fields of (left) table
        @COLUMN_NAME                     NVARCHAR(255), -- will hold column names of the (left) table
        @sql                             NVARCHAR(MAX), -- sql statement variable
        @getdate                         NVARCHAR(17),  -- transform getdate() to YYYYMMDDHHMMSSMMM
        @tmp_table                       NVARCHAR(255), -- will hold the name of a physical temp table
        @pk_separator                    NVARCHAR(1),   -- separator used in @PK_COLUMN_NAME if provided (only checking obvious ones ,;|-)
        @COLUMN_NAME_DATA_TYPE           NVARCHAR(100), -- needed for insert statements to convert to right text string
        @own_pk                          BIT = 0        -- check if table has PK (0) or if provided PK will be used (1)




set @ignore_field_input=replace(replace(replace(@ignore_field_input,' ',''),'[',''),']','')
set @PK_COLUMN_NAME=    replace(replace(replace(@PK_COLUMN_NAME,    ' ',''),'[',''),']','')

-- first we remove all linefeeds from the user query
set @fullquery=replace(replace(replace(@fullquery,char(10),''),char(13),' '),'  ',' ')
set @table_N_where_clause=@fullquery
if charindex ('order by' , @table_N_where_clause) > 0
    print ' WARNING:        ORDER BY NOT ALLOWED IN UPDATE ...'
if @PK_COLUMN_NAME <> ''
    select ' WARNING:        IF you select your own primary keys, make double sure before doing the update statements below!! '
--print @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) = 0
    set @table_N_where_clause= 'select * from ' + @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) > 0
    exec (@table_N_where_clause)

set @table_N_where_clause=rtrim(ltrim(substring(@table_N_where_clause,CHARINDEX(' from ', @table_N_where_clause )+6, 4000)))
--print @table_N_where_clause 
set @table_name=left(@table_N_where_clause,CHARINDEX(' ', @table_N_where_clause )-1)


IF CHARINDEX('where ', @table_N_where_clause) > 0             SELECT @table_alias = LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(@table_N_where_clause,1, CHARINDEX('where ', @table_N_where_clause )-1),'(nolock)',''),@table_name,'')))
IF CHARINDEX('join ',  @table_alias) > 0                      SELECT @table_alias = SUBSTRING(@table_alias, 1, CHARINDEX(' ', @table_alias)-1) -- until next space
IF LEN(@table_alias) = 0                                      SELECT @table_alias = @table_name
IF (charindex (' *' , @fullquery) > 0 or charindex (@table_alias+'.*' , @fullquery) > 0 )     set @list_all_cols=1
/*       
       print @fullquery     
       print @table_alias
       print @table_N_where_clause
       print @table_name
*/


-- Prepare PK condition
        SELECT @table_schema = CASE WHEN CHARINDEX('.',@table_name) > 0 THEN LEFT(@table_name, CHARINDEX('.',@table_name)-1) ELSE 'dbo' END

        SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
        WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
        AND TABLE_SCHEMA = @table_schema

        SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
        WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
        AND i1.TABLE_SCHEMA = @table_schema

            -- if no primary keys exist then we try for identity columns
                IF @PK_condition is null SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
                FROM  INFORMATION_SCHEMA.COLUMNS
                WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 
                AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
                AND TABLE_SCHEMA = @table_schema

                IF @pkstring is null SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
                FROM  INFORMATION_SCHEMA.COLUMNS
                WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 
                AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
                AND TABLE_SCHEMA = @table_schema
-- Same but in form of a table

        INSERT INTO @stringsplit_table
        SELECT 'pk_'+i1.COLUMN_NAME as col, i2.DATA_TYPE as dtype
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
        inner join INFORMATION_SCHEMA.COLUMNS i2
        on  i1.TABLE_NAME = i2.TABLE_NAME AND i1.TABLE_SCHEMA =  i2.TABLE_SCHEMA
        WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
        AND i1.TABLE_SCHEMA = @table_schema

                -- if no primary keys exist then we try for identity columns
                IF 0=(select count(*) from @stringsplit_table) INSERT INTO @stringsplit_table
                SELECT 'pk_'+i2.COLUMN_NAME as col, i2.DATA_TYPE as dtype
                FROM INFORMATION_SCHEMA.COLUMNS i2
                WHERE COLUMNPROPERTY(object_id(i2.TABLE_SCHEMA+'.'+i2.TABLE_NAME), i2.COLUMN_NAME, 'IsIdentity') = 1 
                AND i2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
                AND i2.TABLE_SCHEMA = @table_schema

-- NOW handling the primary key given as parameter to the main batch

SELECT @pk_separator = ',' -- take this as default, we'll check lower if it's a different one
IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME <> ''
BEGIN
    IF CHARINDEX(';', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = ';'
    ELSE IF CHARINDEX('|', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = '|'
    ELSE IF CHARINDEX('-', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = '-'

    SELECT @PK_condition = NULL -- make sure to make it NULL, in case it was ''
    INSERT INTO @stringsplit_table
    SELECT LTRIM(RTRIM(x.value)) , 'datetime'  FROM STRING_SPLIT(@PK_COLUMN_NAME, @pk_separator) x  
    SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME(x.col) + ' = ' + replace(QUOTENAME(x.col,'{'),'{','{pk_')
      FROM @stringsplit_table x

    SELECT @PK_COLUMN_NAME = NULL -- make sure to make it NULL, in case it was ''
    SELECT @PK_COLUMN_NAME = ISNULL(@PK_COLUMN_NAME + ', ', '') + QUOTENAME(x.col) + ' as pk_' + x.col
      FROM @stringsplit_table x
    --print 'pkcolumns  '+ isnull(@PK_COLUMN_NAME,'')
    update @stringsplit_table set col='pk_' + col
    SELECT @own_pk = 1
END
ELSE IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME = ''
BEGIN
    RAISERROR('No Primary key or Identity column available on table. Add some columns as the third parameter when calling this SP to make your own temporary PK., also remove  [] from tablename',17,1)
END


-- IF there are no primary keys or an identity key in the table active, then use the given columns as a primary key


if isnull(@pkstring,'')   = ''  set    @pkstring  = @PK_COLUMN_NAME
IF ISNULL(@pkstring, '') <> ''  SELECT @fullquery = REPLACE(@fullquery, 'SELECT ','SELECT ' + @pkstring + ',' )
--print @pkstring




-- ignore fields for UPDATE STATEMENT (not ignored for the insert statement,  in iserts statement we ignore only identity Columns and the columns provided with the main stored proc )
-- Place here all fields that you know can not be converted to nvarchar() values correctly, an thus should not be scripted for updates)
-- for insert we will take these fields along, although they will be incorrectly represented!!!!!!!!!!!!!.
SELECT           ignore_field = 'uniqueidXXXX' INTO #ignore 
UNION ALL SELECT ignore_field = 'UPDATEMASKXXXX'
UNION ALL SELECT ignore_field = 'UIDXXXXX'
UNION ALL SELECT value FROM  string_split(@ignore_field_input,@pk_separator)




SELECT @getdate = REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(30), GETDATE(), 121), '-', ''), ' ', ''), ':', ''), '.', '')
SELECT @tmp_table = 'Release_DATA__' + @getdate + '__' + REPLACE(@table_name,@table_schema+'.','') 

SET @sql = replace( @fullquery,  ' from ',  ' INTO ' + @tmp_table +' from ')
----print (@sql)
exec (@sql)



SELECT @sql = N'alter table ' + @tmp_table + N'  add update_stmt1  nvarchar(max), update_stmt2 nvarchar(max) , update_stmt3 nvarchar(max)'
EXEC (@sql)

-- Prepare update field list (only columns from the temp table are taken if they also exist in the base table to update)
SELECT @update_list1 = ISNULL(@update_list1 + ', ', '') + 
                      CASE WHEN C1.COLUMN_NAME = 'ModifiedBy' THEN '[ModifiedBy] = left(right(replace(CONVERT(VARCHAR(19),[Modified],121),''''-'''',''''''''),19) +''''-''''+right(SUSER_NAME(),30),50)'
                           WHEN C1.COLUMN_NAME = 'Modified' THEN '[Modified] = GETDATE()'
                           ELSE QUOTENAME(C1.COLUMN_NAME) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
                      END
FROM INFORMATION_SCHEMA.COLUMNS c1
inner join INFORMATION_SCHEMA.COLUMNS c2
on c1.COLUMN_NAME =c2.COLUMN_NAME and c2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')  AND c2.TABLE_SCHEMA = @table_schema
WHERE c1.TABLE_NAME = @tmp_table --REPLACE(@table_name,@table_schema+'.','') 
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND COLUMNPROPERTY(object_id(c2.TABLE_SCHEMA+'.'+c2.TABLE_NAME), c2.COLUMN_NAME, 'IsIdentity') <> 1
AND NOT EXISTS (SELECT 1 
                  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku 
                 WHERE 1 = 1
                   AND ku.TABLE_NAME = c2.TABLE_NAME
                   AND ku.TABLE_SCHEMA = c2.TABLE_SCHEMA
                   AND ku.COLUMN_NAME = c2.COLUMN_NAME
                   AND OBJECTPROPERTY(OBJECT_ID(ku.CONSTRAINT_SCHEMA + '.' + QUOTENAME(ku.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1)
AND NOT EXISTS (SELECT 1 FROM @stringsplit_table x WHERE x.col = c2.COLUMN_NAME AND @own_pk = 1)

-- Prepare update field list  (here we only take columns that commence with a #, as this is our queue for doing the update that comes from an inner joined table)
SELECT @update_list2 = ISNULL(@update_list2 + ', ', '') +  QUOTENAME(replace( C1.COLUMN_NAME,'#','')) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
FROM INFORMATION_SCHEMA.COLUMNS c1
WHERE c1.TABLE_NAME = @tmp_table --AND c1.TABLE_SCHEMA = @table_schema
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND c1.COLUMN_NAME like '#%'

-- similar for select list, but take all fields
SELECT @select_list = ISNULL(@select_list + ', ', '') + QUOTENAME(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
AND TABLE_SCHEMA = @table_schema
AND COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') <> 1  -- Identity columns are filled automatically by MSSQL, not needed at Insert statement
AND QUOTENAME(c.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here


SELECT @PK_condition = REPLACE(@PK_condition, '[pk_', '[')
set @select_list='if not exists (select * from '+  REPLACE(@table_name,@table_schema+'.','') +'  where '+  @PK_condition +')  INSERT INTO '+ REPLACE(@table_name,@table_schema+'.','')   + '('+ @select_list  + ') VALUES (' + replace(replace(@select_list,'[','{'),']','}') + ')'
SELECT @sql = N'UPDATE ' + @tmp_table + ' set update_stmt1 = ''' + @select_list + '''' 
if @list_all_cols=1 EXEC (@sql)



--print 'select==========  ' + @select_list
--print 'update==========  ' + @update_list1


SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt2 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name + 
                                          N' SET ' + @update_list1 + N''' + ''' +
                                          N' WHERE ' + @PK_condition + N''') ' 

EXEC (@sql)
--print @sql



SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt3 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name + 
                                          N' SET ' + @update_list2 + N''' + ''' +
                                          N' WHERE ' + @PK_condition + N''') ' 

EXEC (@sql)
--print @sql


-- LOOPING OVER ALL base tables column for the INSERT INTO .... VALUES
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
    SELECT COLUMN_NAME, DATA_TYPE
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME = (CASE WHEN @list_all_cols=0 THEN @tmp_table ELSE REPLACE(@table_name,@table_schema+'.','') END )
    AND TABLE_SCHEMA = @table_schema
        UNION--pned
    SELECT col, 'datetime' FROM @stringsplit_table

OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @sql = 
    CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
    ELSE  
                  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
    END
    ----PRINT @sql
    EXEC (@sql)
    FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns

--SELECT col FROM @stringsplit_table -- these are the primary keys

-- LOOPING OVER ALL temp tables column for the Update values
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
    SELECT COLUMN_NAME,DATA_TYPE
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME =  @tmp_table --    AND TABLE_SCHEMA = @table_schema
       UNION--pned
    SELECT col, 'datetime' FROM @stringsplit_table

OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @sql = 
    CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL''))  ' 
    ELSE    
                  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
    END
    EXEC (@sql)
    ----print @sql
    FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns

SET @sql = 'Select * from  ' + @tmp_table + ';'
--exec (@sql)

SELECT @sql = N'
IF OBJECT_ID(''' + @tmp_table + N''', ''U'') IS NOT NULL
BEGIN
       SELECT   ''USE ' + DB_NAME()  + '''  as executelist 
              UNION ALL
       SELECT   ''GO ''  as executelist 
              UNION ALL
       SELECT   '' /*PRESCRIPT CHECK  */              ' + replace(@fullquery,'''','''''')+''' as executelist 
              UNION ALL
       SELECT update_stmt1 as executelist FROM ' + @tmp_table + N' where update_stmt1 is not null
              UNION ALL
       SELECT update_stmt2 as executelist FROM ' + @tmp_table + N' where update_stmt2 is not null
              UNION ALL
       SELECT isnull(update_stmt3, '' add more columns inn query please'')  as executelist FROM ' + @tmp_table + N' where update_stmt3 is not null
              UNION ALL
       SELECT ''--EXEC usp_AddInstalledScript 5, 5, 1, 1, 1, ''''' + @tmp_table + '.sql'''', 2 ''  as executelist
              UNION ALL 
       SELECT   '' /*VERIFY WITH:  */              ' + replace(@fullquery,'''','''''')+''' as executelist 
              UNION ALL
       SELECT ''-- SCRIPT LOCATION:      F:\CopyPaste\++Distributionpoint++\Release_Management\' + @tmp_table + '.sql''  as executelist   
END'
exec (@sql)

SET @sql = 'DROP TABLE ' + @tmp_table + ';'
exec (@sql)
牵强ㄟ 2024-07-30 06:50:43

为什么不在使用数据之前备份数据,然后在需要刷新时恢复呢?

如果您必须生成插入,请尝试: http://vyaskn.tripod.com/code.htm#inserts

why not just backup the data before your work with it, then restore when you want it to be refreshed?

if you must generate inserts try: http://vyaskn.tripod.com/code.htm#inserts

网名女生简单气质 2024-07-30 06:50:43

如果您更愿意使用 Google 表格,请使用 SeekWell 将表格发送到表格,然后插入计划中的行,因为它们被添加到工作表中。

请参阅此处了解操作步骤步骤流程 ,或在此处观看该功能的视频演示

If you'd rather use Google Sheets, use SeekWell to Send the table to a Sheet, then insert rows on a schedule, as they're added to the Sheet.

See here for the step by step process , or watch a video demo of the feature here.

吹梦到西洲 2024-07-30 06:50:43

您的生产数据库中还有数据吗? 如果是这样,您可以通过 DTS 设置数据的周期刷新。 我们每周都会在周末进行测试,每周都能获得干净、真实的数据进行测试真是太好了。

如果您还没有生产,那么您应该创建一个他们想要的数据库(新鲜的)。 然后,复制该数据库并使用新创建的数据库作为测试环境。 当您想要干净版本时,只需再次复制干净版本即可鲍勃是你的叔叔

Do you have data in a production database yet? If so, you could setup a period refresh of the data via DTS. We do ours weekly on the weekends and it is very nice to have clean, real data every week for our testing.

If you don't have production yet, then you should create a database that is they want you want it (fresh). Then, duplicate that database and use that newly created database as your test environment. When you want the clean version, simply duplicate your clean one again and Bob's your uncle.

眼眸里的那抹悲凉 2024-07-30 06:50:43

Azure Data Studio - 简单数据脚本编写器扩展。

INSERT ... 之后,它会为每行生成 UNION ALL SELECT

Azure Data Studio UI 基于 VSCode,我发现它直观且快速,包括这个 OSS 扩展。

Azure Data Studio - Simple Data Scripter extension.

After INSERT ... it generates UNION ALL SELECT per row.

Azure Data Studio UI is based on VSCode, and I find it to be intuitive and fast, including this OSS extension.

余生一个溪 2024-07-30 06:50:43

不确定我是否正确理解你的问题。

如果您在 MS-Access 中有数据,并且希望将其移动到 SQL Server - 您可以使用 DTS。
而且,我想您可以使用 SQL 探查器来查看所有正在执行的 INSERT 语句。

Not sure, if I understand your question correctly.

If you have data in MS-Access, which you want to move it to SQL Server - you could use DTS.
And, I guess you could use SQL profiler to see all the INSERT statements going by, I suppose.

不喜欢何必死缠烂打 2024-07-30 06:50:43

我对此也进行了很多研究,但我无法得到具体的解决方案。 目前我采用的方法是从SQL Server Managment studio复制excel中的内容,然后将数据导入到Oracle-TOAD中,然后生成插入语句

I have also researched lot on this, but I could not get the concrete solution for this. Currently the approach I follow is copy the contents in excel from SQL Server Managment studio and then import the data into Oracle-TOAD and then generate the insert statements

德意的啸 2024-07-30 06:50:43

您可以根据需要使其变得困难或简单。 我更喜欢后者。

如果您已经有一个数据集,您所要做的就是在 MS Access 中添加一个操作查询:

insert into Table1("column list here") select "column list here" from Table2

注意:Table2 可以是一个查询,而 Table1 和 Table2可以是 MS Access 表或 Sql Server 表

You can make it as difficult or as simple as you want. I prefer the latter.

If you already have a dataset, all you have to do is add an action query in MS Access:

insert into Table1("column list here") select "column list here" from Table2

NOTE: Table2 could be a query and Table1 and Table2 could be an MS Access table or Sql Server table

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文