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

时间:2009-06-11 17:42:28

标签: sql-server ssms code-generation

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

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

第一部分(删除和重新创建)是一个简单的sql脚本,但最后一部分让我感到畏缩。我想要一个单一的安装脚本,它有一堆INSERT来重新生成虚拟数据。

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

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

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

23 个答案:

答案 0 :(得分:923)

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

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

  1. 右键点击数据库,然后转到任务> 生成脚本
  2. 选择要生成脚本的表(或对象)。
  3. 转到设置脚本选项标签,然后点击高级按钮。
  4. 常规类别中,转到要编写脚本的数据类型
  5. 有3个选项:仅架构仅限数据,以及架构和数据。选择适当的选项,然后单击确定
  6. 然后,您将直接从SSMS获取CREATE TABLE语句和所有INSERT语句。

答案 1 :(得分:81)

我们使用这个存储过程 - 它允许您定位特定的表,并使用where子句。您可以找到文字here

例如,它允许您这样做:

EXEC sp_generate_inserts 'titles'

答案 2 :(得分:41)

如@Mike Ritacco所述,但已针对SSMS 2008 R2进行了更新

  1. 右键单击数据库名称
  2. 选择任务>生成脚本
  3. 根据您的设置,可能会显示介绍页面
  4. 选择“选择特定数据库对象”,
  5. 展开树状视图并检查相关表格
  6. 点击下一步
  7. 点击高级
  8. 在“常规”部分下,为“要编写脚本的数据类型”
  9. 选择适当的选项
  10. 完成向导
  11. 然后,您将直接从SSMS获取数据的所有INSERT语句。

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

    1. 右键单击数据库名称

    2. 选择任务>生成脚本

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

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

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

    6. 单击“下一步”

    7. 点击高级

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

    9. 点击确定

    10. 选择是否要将输出转到新查询,剪贴板或a 文件

    11. 单击“下一步”两次

    12. 您的脚本是根据您在上面选择的设置准备的

    13. 点击完成

答案 3 :(得分:34)

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

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

执行以下步骤:

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

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


"过滤"和#34;脚本"按钮Visual Studio 2013

enter image description here

答案 4 :(得分:27)

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

http://www.ssmstoolspack.com/

答案 5 :(得分:23)

我正在使用SSMS 2008版本10.0.5500.0。在此版本中,作为Generate Scripts向导的一部分,而不是Advanced按钮,下面是屏幕。在这种情况下,我只想插入数据而没有创建语句,所以我不得不更改两个带圆圈的属性Script Options

答案 6 :(得分:13)

答案 7 :(得分:9)

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

INSERT statement(s) generator

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

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

答案 8 :(得分:8)

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 
...

答案 9 :(得分:7)

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

  1. 将以下脚本保存为“filename.ps1”。
  2. 对“CUSTOMIZE ME”下的区域进行自己的修改。
  3. 您可以按任何顺序将表格列表添加到脚本中。
  4. 您可以在Powershell ISE中打开脚本并点击“播放”按钮,或者只是在Powershell命令提示符下执行脚本。
  5. 默认情况下,生成的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()
    

答案 10 :(得分:4)

请勿使用插页,请使用BCP

答案 11 :(得分:4)

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

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

答案 12 :(得分:3)

GenerateData是一个很棒的工具。它也很容易调整,因为源代码可供您使用。一些不错的功能:

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

GUI

答案 13 :(得分:3)

我使用了我在博客上放置的script如何在sql server上生成插入语句程序)。

到目前为止对我有用,虽然它们可能是我尚未发现的错误。

答案 14 :(得分:2)

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

sqlite3 foo.sqlite .dump > foo_as_a_bunch_of_inserts.sql

答案 15 :(得分:1)

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

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

下面的脚本可以做的另一件事是:它甚至可以处理其他表的INNER JOIN作为存储过程的输入语句。作为穷人的发布管理工具,它很方便,它可以一整天都在您输入SQL SELECT语句的指尖上。

原始帖子: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)

答案 16 :(得分:1)

您是否在生产数据库中有数据?如果是这样,您可以通过DTS设置数据的周期刷新。我们每周都会在周末进行测试,每周都有干净,真实的数据供我们测试。

如果您还没有生产,那么您应该创建一个他们想要的数据库(新鲜的)。然后,复制该数据库并使用新创建的数据库作为您的测试环境。如果您想要干净的版本,只需再次复制干净的版本并Bob's your uncle

答案 17 :(得分:0)

为什么不在使用数据之前备份数据,然后在希望刷新数据时进行恢复?

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

答案 18 :(得分:0)

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

答案 19 :(得分:0)

如果您想使用Google表格,请使用SeekWell将表格发送到表格中,然后将它们添加到表格中,然后按计划插入行。

有关逐步过程,请参见here,或在此处观看功能的video demo

答案 20 :(得分:0)

您可以使用我几年前编写的简单且免费的应用程序生成 INSERT MERGE 语句:
Data Script Writer(Windows桌面应用程序)

enter image description here 另外,我最近写了一篇有关这些工具以及利用SSDT来为具有数据的部署数据库使用方法的博客文章。了解更多:
Script and deploy the data for database from SSDT project

答案 21 :(得分:0)

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

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

如果生成的INSERT语句被截断,请在Management Studio选项上检查结果的限制文本长度:“已检索的最大字符数”下的Tools > OptionsQuery Results > SQL Server > Results to Grid,“非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 (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 (47, 39)) -- 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

答案 22 :(得分:0)

如果我理解你的问题,不确定。

如果您有MS-Access中的数据,您想将其移动到SQL Server - 您可以使用DTS 并且,我猜你可以使用SQL分析器来查看所有INSERT语句,我猜想。