{"id":441,"date":"2022-08-31T10:34:00","date_gmt":"2022-08-31T13:34:00","guid":{"rendered":"https:\/\/www.ctasoftware.com.br\/blog\/?p=441"},"modified":"2022-08-30T10:38:36","modified_gmt":"2022-08-30T13:38:36","slug":"procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente","status":"publish","type":"post","link":"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/","title":{"rendered":"Procedure para gerar Inserts a partir de uma tabela existente"},"content":{"rendered":"\n<p>A procedure foi encontrada na internet e desenvolvido pela Narayana Vyas, todos os cr\u00e9ditos para a mesma.<\/p>\n\n\n\n<p>Na procedure j\u00e1 existem alguns exemplos de uso. <\/p>\n\n\n\n<p>Testada at\u00e9 a vers\u00e3o atual 2019 e funciona perfeitamente.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">CREATE PROC [dbo].[sp_generate_inserts]\n(\n    @table_name varchar(776),       -- The table\/view for which the INSERT statements will be generated using the existing data\n    @target_table varchar(776) = NULL,  -- Use this parameter to specify a different table name into which the data will be inserted\n    @include_column_list bit = 1,       -- Use this parameter to include\/ommit column list in the generated INSERT statement\n    @from varchar(800) = NULL,      -- Use this parameter to filter the rows based on a filter condition (using WHERE)\n    @include_timestamp bit = 0,         -- Specify 1 for this parameter, if you want to include the TIMESTAMP\/ROWVERSION column's data in the INSERT statement\n    @debug_mode bit = 0,            -- If @debug_mode is set to 1, the SQL statements constructed by this procedure will be printed for later examination\n    @owner varchar(64) = NULL,      -- Use this parameter if you are not the owner of the table\n    @ommit_images bit = 0,          -- Use this parameter to generate INSERT statements by omitting the 'image' columns\n    @ommit_identity bit = 0,        -- Use this parameter to ommit the identity columns\n    @top int = NULL,            -- Use this parameter to generate INSERT statements only for the TOP n rows\n    @cols_to_include varchar(8000) = NULL,  -- List of columns to be included in the INSERT statement\n    @cols_to_exclude varchar(8000) = NULL,  -- List of columns to be excluded from the INSERT statement\n    @disable_constraints bit = 0,       -- When 1, disables foreign key constraints and enables them after the INSERT statements\n    @ommit_computed_cols bit = 0        -- When 1, computed columns will not be included in the INSERT statement\n\n)\nAS\nBEGIN\n\n\/***********************************************************************************************************\nProcedure:  sp_generate_inserts  (Build 22) \n\nPurpose:    To generate INSERT statements from existing data. \n        These INSERTS can be executed to regenerate the data at some other location.\n        This procedure is also useful to create a database setup, where in you can \n        script your data along with your table definitions.\n\nTested on:  SQL Server 7.0 and SQL Server 2000\n\nDate created:   January 17th 2001 21:52 GMT\n\nDate modified:  May 1st 2002 19:50 GMT\n\nNOTE:       This procedure may not work with tables with too many columns.\n        Results can be unpredictable with huge text columns or SQL Server 2000's sql_variant data types\n        Whenever possible, Use @include_column_list parameter to ommit column list in the INSERT statement, for better results\n        IMPORTANT: This procedure is not tested with internation data (Extended characters or Unicode). If needed\n        you might want to convert the datatypes of character variables in this procedure to their respective unicode counterparts\n        like nchar and nvarchar\n\n\nExample 1:  To generate INSERT statements for table 'titles':\n\n        EXEC sp_generate_inserts 'titles'\n\nExample 2:  To ommit the column list in the INSERT statement: (Column list is included by default)\n        IMPORTANT: If you have too many columns, you are advised to ommit column list, as shown below,\n        to avoid erroneous results\n\n        EXEC sp_generate_inserts 'titles', @include_column_list = 0\n\nExample 3:  To generate INSERT statements for 'titlesCopy' table from 'titles' table:\n\n        EXEC sp_generate_inserts 'titles', 'titlesCopy'\n\nExample 4:  To generate INSERT statements for 'titles' table for only those titles \n        which contain the word 'Computer' in them:\n        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\n\n        EXEC sp_generate_inserts 'titles', @from = \"from titles where title like '%Computer%'\"\n\nExample 5:  To specify that you want to include TIMESTAMP column's data as well in the INSERT statement:\n        (By default TIMESTAMP column's data is not scripted)\n\n        EXEC sp_generate_inserts 'titles', @include_timestamp = 1\n\nExample 6:  To print the debug information:\n\n        EXEC sp_generate_inserts 'titles', @debug_mode = 1\n\nExample 7:  If you are not the owner of the table, use @owner parameter to specify the owner name\n        To use this option, you must have SELECT permissions on that table\n\n        EXEC sp_generate_inserts Nickstable, @owner = 'Nick'\n\nExample 8:  To generate INSERT statements for the rest of the columns excluding images\n        When using this otion, DO NOT set @include_column_list parameter to 0.\n\n        EXEC sp_generate_inserts imgtable, @ommit_images = 1\n\nExample 9:  To generate INSERT statements excluding (ommiting) IDENTITY columns:\n        (By default IDENTITY columns are included in the INSERT statement)\n\n        EXEC sp_generate_inserts mytable, @ommit_identity = 1\n\nExample 10:     To generate INSERT statements for the TOP 10 rows in the table:\n\n        EXEC sp_generate_inserts mytable, @top = 10\n\nExample 11:     To generate INSERT statements with only those columns you want:\n\n        EXEC sp_generate_inserts titles, @cols_to_include = \"'title','title_id','au_id'\"\n\nExample 12:     To generate INSERT statements by omitting certain columns:\n\n        EXEC sp_generate_inserts titles, @cols_to_exclude = \"'title','title_id','au_id'\"\n\nExample 13: To avoid checking the foreign key constraints while loading data with INSERT statements:\n\n        EXEC sp_generate_inserts titles, @disable_constraints = 1\n\nExample 14:     To exclude computed columns from the INSERT statement:\n        EXEC sp_generate_inserts MyTable, @ommit_computed_cols = 1\n***********************************************************************************************************\/\n\nSET NOCOUNT ON\n\n--Making sure user only uses either @cols_to_include or @cols_to_exclude\nIF ((@cols_to_include IS NOT NULL) AND (@cols_to_exclude IS NOT NULL))\n    BEGIN\n        RAISERROR('Use either @cols_to_include or @cols_to_exclude. Do not use both the parameters at once',16,1)\n        RETURN -1 --Failure. Reason: Both @cols_to_include and @cols_to_exclude parameters are specified\n    END\n\n--Making sure the @cols_to_include and @cols_to_exclude parameters are receiving values in proper format\nIF ((@cols_to_include IS NOT NULL) AND (PATINDEX('''%''',@cols_to_include) = 0))\n    BEGIN\n        RAISERROR('Invalid use of @cols_to_include property',16,1)\n        PRINT 'Specify column names surrounded by single quotes and separated by commas'\n        PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_include = \"''title_id'',''title''\"'\n        RETURN -1 --Failure. Reason: Invalid use of @cols_to_include property\n    END\n\nIF ((@cols_to_exclude IS NOT NULL) AND (PATINDEX('''%''',@cols_to_exclude) = 0))\n    BEGIN\n        RAISERROR('Invalid use of @cols_to_exclude property',16,1)\n        PRINT 'Specify column names surrounded by single quotes and separated by commas'\n        PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_exclude = \"''title_id'',''title''\"'\n        RETURN -1 --Failure. Reason: Invalid use of @cols_to_exclude property\n    END\n\n\n--Checking to see if the database name is specified along wih the table name\n--Your database context should be local to the table for which you want to generate INSERT statements\n--specifying the database name is not allowed\nIF (PARSENAME(@table_name,3)) IS NOT NULL\n    BEGIN\n        RAISERROR('Do not specify the database name. Be in the required database and just specify the table name.',16,1)\n        RETURN -1 --Failure. Reason: Database name is specified along with the table name, which is not allowed\n    END\n\n--Checking for the existence of 'user table' or 'view'\n--This procedure is not written to work on system tables\n--To script the data in system tables, just create a view on the system tables and script the view instead\n\nIF @owner IS NULL\n    BEGIN\n        IF ((OBJECT_ID(@table_name,'U') IS NULL) AND (OBJECT_ID(@table_name,'V') IS NULL)) \n            BEGIN\n                RAISERROR('User table or view not found.',16,1)\n                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.'\n                PRINT 'Make sure you have SELECT permission on that table or view.'\n                RETURN -1 --Failure. Reason: There is no user table or view with this name\n            END\n    END\nELSE\n    BEGIN\n        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)\n            BEGIN\n                RAISERROR('User table or view not found.',16,1)\n                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.'\n                PRINT 'Make sure you have SELECT permission on that table or view.'\n                RETURN -1 --Failure. Reason: There is no user table or view with this name      \n            END\n    END\n\n--Variable declarations\nDECLARE     @Column_ID int,         \n        @Column_List varchar(8000), \n        @Column_Name varchar(128), \n        @Start_Insert varchar(786), \n        @Data_Type varchar(128), \n        @Actual_Values varchar(8000),   --This is the string that will be finally executed to generate INSERT statements\n        @IDN varchar(128)       --Will contain the IDENTITY column's name in the table\n\n--Variable Initialization\nSET @IDN = ''\nSET @Column_ID = 0\nSET @Column_Name = ''\nSET @Column_List = ''\nSET @Actual_Values = ''\n\nIF @owner IS NULL \n    BEGIN\n        SET @Start_Insert = 'INSERT INTO ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' \n    END\nELSE\n    BEGIN\n        SET @Start_Insert = 'INSERT ' + '[' + LTRIM(RTRIM(@owner)) + '].' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']'      \n    END\n\n\n--To get the first column's ID\n\nSELECT  @Column_ID = MIN(ORDINAL_POSITION)  \nFROM    INFORMATION_SCHEMA.COLUMNS (NOLOCK) \nWHERE   TABLE_NAME = @table_name AND\n(@owner IS NULL OR TABLE_SCHEMA = @owner)\n\n\n\n--Loop through all the columns of the table, to get the column names and their data types\nWHILE @Column_ID IS NOT NULL\n    BEGIN\n        SELECT  @Column_Name = QUOTENAME(COLUMN_NAME), \n        @Data_Type = DATA_TYPE \n        FROM    INFORMATION_SCHEMA.COLUMNS (NOLOCK) \n        WHERE   ORDINAL_POSITION = @Column_ID AND \n        TABLE_NAME = @table_name AND\n        (@owner IS NULL OR TABLE_SCHEMA = @owner)\n\n\n\n        IF @cols_to_include IS NOT NULL --Selecting only user specified columns\n        BEGIN\n            IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_include) = 0 \n            BEGIN\n                GOTO SKIP_LOOP\n            END\n        END\n\n        IF @cols_to_exclude IS NOT NULL --Selecting only user specified columns\n        BEGIN\n            IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_exclude) &lt;> 0 \n            BEGIN\n                GOTO SKIP_LOOP\n            END\n        END\n\n        --Making sure to output SET IDENTITY_INSERT ON\/OFF in case the table has an IDENTITY column\n        IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsIdentity')) = 1 \n        BEGIN\n            IF @ommit_identity = 0 --Determing whether to include or exclude the IDENTITY column\n                SET @IDN = @Column_Name\n            ELSE\n                GOTO SKIP_LOOP          \n        END\n\n        --Making sure whether to output computed columns or not\n        IF @ommit_computed_cols = 1\n        BEGIN\n            IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsComputed')) = 1 \n            BEGIN\n                GOTO SKIP_LOOP                  \n            END\n        END\n\n        --Tables with columns of IMAGE data type are not supported for obvious reasons\n        IF(@Data_Type in ('image'))\n            BEGIN\n                IF (@ommit_images = 0)\n                    BEGIN\n                        RAISERROR('Tables with image columns are not supported.',16,1)\n                        PRINT 'Use @ommit_images = 1 parameter to generate INSERTs for the rest of the columns.'\n                        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.'\n                        RETURN -1 --Failure. Reason: There is a column with image data type\n                    END\n                ELSE\n                    BEGIN\n                    GOTO SKIP_LOOP\n                    END\n            END\n\n        --Determining the data type of the column and depending on the data type, the VALUES part of\n        --the INSERT statement is generated. Care is taken to handle columns with NULL values. Also\n        --making sure, not to lose any data from flot, real, money, smallmomey, datetime columns\n        SET @Actual_Values = @Actual_Values  +\n        CASE \n            WHEN @Data_Type IN ('char','varchar','nchar','nvarchar') \n                THEN \n                    'COALESCE('''''''' + REPLACE(RTRIM(' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'\n            WHEN @Data_Type IN ('datetime','datetime2','smalldatetime') \n                THEN \n                    --'COALESCE('''''''' + RTRIM(CONVERT(char,' + @Column_Name + ',109))+'''''''',''NULL'')'\n\t\t\t\t\t'COALESCE('''''''' + REPLACE(CONVERT(char,' + @Column_Name + ',109),'''''''','''''''''''')+'''''''',''NULL'')'\n            WHEN @Data_Type IN ('uniqueidentifier') \n                THEN  \n                    'COALESCE('''''''' + REPLACE(CONVERT(char(255),RTRIM(' + @Column_Name + ')),'''''''','''''''''''')+'''''''',''NULL'')'\n            WHEN @Data_Type IN ('text','ntext') \n                THEN  \n                    'COALESCE('''''''' + REPLACE(CONVERT(char(8000),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'                    \n            WHEN @Data_Type IN ('binary','varbinary') \n                THEN  \n                    'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'  \n            WHEN @Data_Type IN ('timestamp','rowversion') \n                THEN  \n                    CASE \n                        WHEN @include_timestamp = 0 \n                            THEN \n                                '''DEFAULT''' \n                            ELSE \n                                'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'  \n                    END\n            WHEN @Data_Type IN ('float','real','money','smallmoney')\n                THEN\n                    'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' +  @Column_Name  + ',2)' + ')),''NULL'')' \n            ELSE \n                'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' +  @Column_Name  + ')' + ')),''NULL'')' \n        END   + '+' +  ''',''' + ' + '\n\n        --Generating the column list for the INSERT statement\n        SET @Column_List = @Column_List +  @Column_Name + ','   \n\n        SKIP_LOOP: --The label used in GOTO\n\n        SELECT  @Column_ID = MIN(ORDINAL_POSITION) \n        FROM    INFORMATION_SCHEMA.COLUMNS (NOLOCK) \n        WHERE   TABLE_NAME = @table_name AND \n        ORDINAL_POSITION > @Column_ID AND\n        (@owner IS NULL OR TABLE_SCHEMA = @owner)\n\n\n    --Loop ends here!\n    END\n\n--To get rid of the extra characters that got concatenated during the last run through the loop\nSET @Column_List = LEFT(@Column_List,len(@Column_List) - 1)\nSET @Actual_Values = LEFT(@Actual_Values,len(@Actual_Values) - 6)\n\nIF LTRIM(@Column_List) = '' \n    BEGIN\n        RAISERROR('No columns to select. There should at least be one column to generate the output',16,1)\n        RETURN -1 --Failure. Reason: Looks like all the columns are ommitted using the @cols_to_exclude parameter\n    END\n\n--Forming the final string that will be executed, to output the INSERT statements\nIF (@include_column_list &lt;> 0)\n    BEGIN\n        SET @Actual_Values = \n            'SELECT ' +  \n            CASE WHEN @top IS NULL OR @top &lt; 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END + \n            '''' + RTRIM(@Start_Insert) + \n            ' ''+' + '''(' + RTRIM(@Column_List) +  '''+' + ''')''' + \n            ' +''VALUES(''+ ' +  @Actual_Values  + '+'')''' + ' ' + \n            COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')\n    END\nELSE IF (@include_column_list = 0)\n    BEGIN\n        SET @Actual_Values = \n            'SELECT ' + \n            CASE WHEN @top IS NULL OR @top &lt; 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END + \n            '''' + RTRIM(@Start_Insert) + \n            ' '' +''VALUES(''+ ' +  @Actual_Values + '+'')''' + ' ' + \n            COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')\n    END \n\n--Determining whether to ouput any debug information\nIF @debug_mode =1\n    BEGIN\n        PRINT '\/*****START OF DEBUG INFORMATION*****'\n        PRINT 'Beginning of the INSERT statement:'\n        PRINT @Start_Insert\n        PRINT ''\n        PRINT 'The column list:'\n        PRINT @Column_List\n        PRINT ''\n        PRINT 'The SELECT statement executed to generate the INSERTs'\n        PRINT @Actual_Values\n        PRINT ''\n        PRINT '*****END OF DEBUG INFORMATION*****\/'\n        PRINT ''\n    END\n\nPRINT '--INSERTs generated by ''sp_generate_inserts'' stored procedure written by Vyas'\nPRINT '--Build number: 22'\nPRINT '--Problems\/Suggestions? Contact Vyas @ vyaskn@hotmail.com'\nPRINT '--http:\/\/vyaskn.tripod.com'\nPRINT ''\nPRINT 'SET NOCOUNT ON'\nPRINT ''\n\n\n--Determining whether to print IDENTITY_INSERT or not\nIF (@IDN &lt;> '')\n    BEGIN\n        PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' ON'\n        PRINT 'GO'\n        PRINT ''\n    END\n\n\nIF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)\n    BEGIN\n        IF @owner IS NULL\n            BEGIN\n                SELECT  'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'\n            END\n        ELSE\n            BEGIN\n                SELECT  'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'\n            END\n\n        PRINT 'GO'\n    END\n\nPRINT ''\nPRINT 'PRINT ''Inserting values into ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' + ''''\n\n\n--All the hard work pays off here!!! You'll get your INSERT statements, when the next line executes!\nEXEC (@Actual_Values)\n\nPRINT 'PRINT ''Done'''\nPRINT ''\n\n\nIF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)\n    BEGIN\n        IF @owner IS NULL\n            BEGIN\n                SELECT  'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL'  AS '--Code to enable the previously disabled constraints'\n            END\n        ELSE\n            BEGIN\n                SELECT  'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL' AS '--Code to enable the previously disabled constraints'\n            END\n\n        PRINT 'GO'\n    END\n\nPRINT ''\nIF (@IDN &lt;> '')\n    BEGIN\n        PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' OFF'\n        PRINT 'GO'\n    END\n\nPRINT 'SET NOCOUNT OFF'\n\n\nSET NOCOUNT OFF\nRETURN 0 --Success. We are done!\nEND\n\nGO\n\n\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Procedure para gerar Inserts a partir de uma tabela existente<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false}}},"categories":[4],"tags":[28,35,5],"jetpack_publicize_connections":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.1 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Procedure para gerar Inserts a partir de uma tabela existente - CTASoftware Blog<\/title>\n<meta name=\"description\" content=\"CTASoftware Blog Procedure para gerar Inserts a partir de uma tabela existente\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/\" \/>\n<meta property=\"og:locale\" content=\"pt_BR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Procedure para gerar Inserts a partir de uma tabela existente - CTASoftware Blog\" \/>\n<meta property=\"og:description\" content=\"CTASoftware Blog Procedure para gerar Inserts a partir de uma tabela existente\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/\" \/>\n<meta property=\"og:site_name\" content=\"CTASoftware Blog\" \/>\n<meta property=\"article:published_time\" content=\"2022-08-31T13:34:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-08-30T13:38:36+00:00\" \/>\n<meta name=\"author\" content=\"Everton Gon\u00e7alves\" \/>\n<meta name=\"twitter:label1\" content=\"Escrito por\" \/>\n\t<meta name=\"twitter:data1\" content=\"Everton Gon\u00e7alves\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. tempo de leitura\" \/>\n\t<meta name=\"twitter:data2\" content=\"14 minutos\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/\"},\"author\":{\"name\":\"Everton Gon\u00e7alves\",\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/#\/schema\/person\/34f7fa2c76834d8410f6dd43e26fd3e4\"},\"headline\":\"Procedure para gerar Inserts a partir de uma tabela existente\",\"datePublished\":\"2022-08-31T13:34:00+00:00\",\"dateModified\":\"2022-08-30T13:38:36+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/\"},\"wordCount\":45,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/#organization\"},\"keywords\":[\"Procedure\",\"SQL\",\"SQL Server\"],\"articleSection\":[\"SQL\"],\"inLanguage\":\"pt-BR\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/\",\"url\":\"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/\",\"name\":\"Procedure para gerar Inserts a partir de uma tabela existente - CTASoftware Blog\",\"isPartOf\":{\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/#website\"},\"datePublished\":\"2022-08-31T13:34:00+00:00\",\"dateModified\":\"2022-08-30T13:38:36+00:00\",\"description\":\"CTASoftware Blog Procedure para gerar Inserts a partir de uma tabela existente\",\"breadcrumb\":{\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/#breadcrumb\"},\"inLanguage\":\"pt-BR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"In\u00edcio\",\"item\":\"https:\/\/www.ctasoftware.com.br\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Procedure para gerar Inserts a partir de uma tabela existente\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/#website\",\"url\":\"https:\/\/www.ctasoftware.com.br\/blog\/\",\"name\":\"CTASoftware Blog\",\"description\":\"Para Desenvolvedores De Software\",\"publisher\":{\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.ctasoftware.com.br\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"pt-BR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/#organization\",\"name\":\"CTASoftware\",\"url\":\"https:\/\/www.ctasoftware.com.br\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"pt-BR\",\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/i0.wp.com\/www.ctasoftware.com.br\/blog\/wp-content\/uploads\/2023\/06\/logocta.png?fit=225%2C44&ssl=1\",\"contentUrl\":\"https:\/\/i0.wp.com\/www.ctasoftware.com.br\/blog\/wp-content\/uploads\/2023\/06\/logocta.png?fit=225%2C44&ssl=1\",\"width\":225,\"height\":44,\"caption\":\"CTASoftware\"},\"image\":{\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/#\/schema\/person\/34f7fa2c76834d8410f6dd43e26fd3e4\",\"name\":\"Everton Gon\u00e7alves\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"pt-BR\",\"@id\":\"https:\/\/www.ctasoftware.com.br\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/3e5e7fe964521f618a2b09d3fbb7800f?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/3e5e7fe964521f618a2b09d3fbb7800f?s=96&d=mm&r=g\",\"caption\":\"Everton Gon\u00e7alves\"},\"description\":\"http:\/\/www.ctasoftware.com.br\",\"sameAs\":[\"http:\/\/www.ctasoftware.com.br\"],\"url\":\"https:\/\/www.ctasoftware.com.br\/blog\/author\/everton-goncalves\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Procedure para gerar Inserts a partir de uma tabela existente - CTASoftware Blog","description":"CTASoftware Blog Procedure para gerar Inserts a partir de uma tabela existente","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/","og_locale":"pt_BR","og_type":"article","og_title":"Procedure para gerar Inserts a partir de uma tabela existente - CTASoftware Blog","og_description":"CTASoftware Blog Procedure para gerar Inserts a partir de uma tabela existente","og_url":"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/","og_site_name":"CTASoftware Blog","article_published_time":"2022-08-31T13:34:00+00:00","article_modified_time":"2022-08-30T13:38:36+00:00","author":"Everton Gon\u00e7alves","twitter_misc":{"Escrito por":"Everton Gon\u00e7alves","Est. tempo de leitura":"14 minutos"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/#article","isPartOf":{"@id":"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/"},"author":{"name":"Everton Gon\u00e7alves","@id":"https:\/\/www.ctasoftware.com.br\/blog\/#\/schema\/person\/34f7fa2c76834d8410f6dd43e26fd3e4"},"headline":"Procedure para gerar Inserts a partir de uma tabela existente","datePublished":"2022-08-31T13:34:00+00:00","dateModified":"2022-08-30T13:38:36+00:00","mainEntityOfPage":{"@id":"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/"},"wordCount":45,"commentCount":0,"publisher":{"@id":"https:\/\/www.ctasoftware.com.br\/blog\/#organization"},"keywords":["Procedure","SQL","SQL Server"],"articleSection":["SQL"],"inLanguage":"pt-BR","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/","url":"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/","name":"Procedure para gerar Inserts a partir de uma tabela existente - CTASoftware Blog","isPartOf":{"@id":"https:\/\/www.ctasoftware.com.br\/blog\/#website"},"datePublished":"2022-08-31T13:34:00+00:00","dateModified":"2022-08-30T13:38:36+00:00","description":"CTASoftware Blog Procedure para gerar Inserts a partir de uma tabela existente","breadcrumb":{"@id":"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/#breadcrumb"},"inLanguage":"pt-BR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.ctasoftware.com.br\/blog\/procedure-para-gerar-inserts-a-partir-de-uma-tabela-existente\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"In\u00edcio","item":"https:\/\/www.ctasoftware.com.br\/blog\/"},{"@type":"ListItem","position":2,"name":"Procedure para gerar Inserts a partir de uma tabela existente"}]},{"@type":"WebSite","@id":"https:\/\/www.ctasoftware.com.br\/blog\/#website","url":"https:\/\/www.ctasoftware.com.br\/blog\/","name":"CTASoftware Blog","description":"Para Desenvolvedores De Software","publisher":{"@id":"https:\/\/www.ctasoftware.com.br\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.ctasoftware.com.br\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"pt-BR"},{"@type":"Organization","@id":"https:\/\/www.ctasoftware.com.br\/blog\/#organization","name":"CTASoftware","url":"https:\/\/www.ctasoftware.com.br\/blog\/","logo":{"@type":"ImageObject","inLanguage":"pt-BR","@id":"https:\/\/www.ctasoftware.com.br\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/i0.wp.com\/www.ctasoftware.com.br\/blog\/wp-content\/uploads\/2023\/06\/logocta.png?fit=225%2C44&ssl=1","contentUrl":"https:\/\/i0.wp.com\/www.ctasoftware.com.br\/blog\/wp-content\/uploads\/2023\/06\/logocta.png?fit=225%2C44&ssl=1","width":225,"height":44,"caption":"CTASoftware"},"image":{"@id":"https:\/\/www.ctasoftware.com.br\/blog\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/www.ctasoftware.com.br\/blog\/#\/schema\/person\/34f7fa2c76834d8410f6dd43e26fd3e4","name":"Everton Gon\u00e7alves","image":{"@type":"ImageObject","inLanguage":"pt-BR","@id":"https:\/\/www.ctasoftware.com.br\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/3e5e7fe964521f618a2b09d3fbb7800f?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/3e5e7fe964521f618a2b09d3fbb7800f?s=96&d=mm&r=g","caption":"Everton Gon\u00e7alves"},"description":"http:\/\/www.ctasoftware.com.br","sameAs":["http:\/\/www.ctasoftware.com.br"],"url":"https:\/\/www.ctasoftware.com.br\/blog\/author\/everton-goncalves\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p6ACmG-77","jetpack-related-posts":[{"id":248,"url":"https:\/\/www.ctasoftware.com.br\/blog\/gerar-query-insert-automaticamente\/","url_meta":{"origin":441,"position":0},"title":"Gerar Query Insert Automaticamente","author":"Everton Gon\u00e7alves","date":"30 de maio de 2017","format":false,"excerpt":"A procedure abaixo cria query INSERT a partir dos registros de uma tabela no SQL Server. [sql] CREATE PROC [dbo].[InsertGenerator] (@tableName varchar(100)) as --Declare a cursor to retrieve column specific information --for the specified table DECLARE cursCol CURSOR FAST_FORWARD FOR SELECT column_name,data_type FROM information_schema.columns WHERE table_name = @tableName OPEN cursCol\u2026","rel":"","context":"Em &quot;SQL&quot;","block_context":{"text":"SQL","link":"https:\/\/www.ctasoftware.com.br\/blog\/category\/sql\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":150,"url":"https:\/\/www.ctasoftware.com.br\/blog\/criar-classe-de-entidade-a-partir-de-tabela-sql-server\/","url_meta":{"origin":441,"position":1},"title":"Criar classe de entidade a partir de tabela SQL Server","author":"Everton Gon\u00e7alves","date":"31 de mar\u00e7o de 2015","format":false,"excerpt":"Disponibilizo abaixo um script para gera\u00e7\u00e3o de classes de entidade (BO, BE, VO) como comumente s\u00e3o chamadas atrav\u00e9s de script SQL Server. CREATE PROCEDURE [dbo].[GeraVO] @tabela varchar(250) AS BEGIN SET NOCOUNT ON; declare @TableName sysname = @tabela declare @Result varchar(max) = 'public class ' + @TableName + ' {' select\u2026","rel":"","context":"Em &quot;.NET&quot;","block_context":{"text":".NET","link":"https:\/\/www.ctasoftware.com.br\/blog\/category\/net\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":147,"url":"https:\/\/www.ctasoftware.com.br\/blog\/trabalhando-com-data-sql-server\/","url_meta":{"origin":441,"position":2},"title":"Trabalhando com Data SQL Server","author":"Everton Gon\u00e7alves","date":"24 de mar\u00e7o de 2015","format":false,"excerpt":"Neste post est\u00e1 listado como utilizar o CONVERT para retornar o conte\u00fado do campo data: Execute o comando abaixo no SQL Server e observe o resultado, voc\u00ea ir\u00e1 ver que o resultado ser\u00e1 baseado na data atual da execu\u00e7\u00e3o do script. Para utilizar em um campo de sua tabela substitua\u2026","rel":"","context":"Em &quot;SQL&quot;","block_context":{"text":"SQL","link":"https:\/\/www.ctasoftware.com.br\/blog\/category\/sql\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":80,"url":"https:\/\/www.ctasoftware.com.br\/blog\/criar-tabelas-temporarias-sql-server\/","url_meta":{"origin":441,"position":3},"title":"Criar Tabelas Tempor\u00e1rias SQL Server","author":"Everton Gon\u00e7alves","date":"23 de agosto de 2012","format":false,"excerpt":"As vezes nos deparamos com a situa\u00e7\u00e3o que devemos criar uma tabela tempor\u00e1ria no SQL Server em seguida descartar. Neste caso criamos a tabela da seguinte maneira CREATE TABLE #NomeTabelaTemporaria( campo1 INT NOT NULL; campo2 VARCHAR(250) NULL; ... ); Ap\u00f3s a cria\u00e7\u00e3o da tabela poderemos realizar nossas a\u00e7\u00f5es. Vale a\u2026","rel":"","context":"Em &quot;SQL&quot;","block_context":{"text":"SQL","link":"https:\/\/www.ctasoftware.com.br\/blog\/category\/sql\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":165,"url":"https:\/\/www.ctasoftware.com.br\/blog\/funcoes-de-data-sql-server\/","url_meta":{"origin":441,"position":4},"title":"Fun\u00e7\u00f5es de Data SQL Server","author":"Everton Gon\u00e7alves","date":"25 de agosto de 2015","format":false,"excerpt":"Algumas sugest\u00f5es de como trabalhar com datas no SQL Server DECLARE @getdate DATETIME; SET @getdate = GETDATE(); SELECT CAST('1) Data Processada' AS VARCHAR(50)), @getdate UNION SELECT CAST('2) Primeiro dia do m\u00eas' AS VARCHAR(50)), DATEADD(mm, DATEDIFF(mm, 0, @getdate), 0) UNION SELECT CAST('3) Primeiro dia da semana' AS VARCHAR(50)), DATEADD(wk, DATEDIFF(wk, 0,\u2026","rel":"","context":"Em &quot;SQL&quot;","block_context":{"text":"SQL","link":"https:\/\/www.ctasoftware.com.br\/blog\/category\/sql\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":447,"url":"https:\/\/www.ctasoftware.com.br\/blog\/obter-nome-e-sobrenome-consulta-sql-server\/","url_meta":{"origin":441,"position":5},"title":"Obter nome e sobrenome consulta SQL Server","author":"Everton Gon\u00e7alves","date":"4 de janeiro de 2023","format":false,"excerpt":"Obter nome e sobrenome a partir de um campo Nome Completo (FullName)","rel":"","context":"Em &quot;MySQL&quot;","block_context":{"text":"MySQL","link":"https:\/\/www.ctasoftware.com.br\/blog\/category\/mysql\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/www.ctasoftware.com.br\/blog\/wp-json\/wp\/v2\/posts\/441"}],"collection":[{"href":"https:\/\/www.ctasoftware.com.br\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.ctasoftware.com.br\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.ctasoftware.com.br\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ctasoftware.com.br\/blog\/wp-json\/wp\/v2\/comments?post=441"}],"version-history":[{"count":1,"href":"https:\/\/www.ctasoftware.com.br\/blog\/wp-json\/wp\/v2\/posts\/441\/revisions"}],"predecessor-version":[{"id":442,"href":"https:\/\/www.ctasoftware.com.br\/blog\/wp-json\/wp\/v2\/posts\/441\/revisions\/442"}],"wp:attachment":[{"href":"https:\/\/www.ctasoftware.com.br\/blog\/wp-json\/wp\/v2\/media?parent=441"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.ctasoftware.com.br\/blog\/wp-json\/wp\/v2\/categories?post=441"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.ctasoftware.com.br\/blog\/wp-json\/wp\/v2\/tags?post=441"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}