Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7897489
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T08:10:46+00:00 2026-06-03T08:10:46+00:00

I have a table of lookup data that was changed in location A and

  • 0

I have a table of lookup data that was changed in “location A” and I need to update the same named table in “location B”. I am thinking that if I had a way to read the table (80k rows) line by line into a properly formatted string, and create an output file of/with a merge statement (“converting” the table into a CTE), then I could have something slick.

All ideas (or pointers from those who have already done something similar) on this idea are appreciated. Thanks. I am using SQL Server Express 2012.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T08:10:47+00:00Added an answer on June 3, 2026 at 8:10 am

    I use this helper script to manage small lookup tables between environments. 80k rows isn’t huge by any means but it is not insignificant. Conrad has laid out a solid plan for moving large amounts of data.

    If you do choose to go the generated merge route hopefully this helps you:

    declare @TableName nvarchar(128) = 'dbo.YourTable';
    
    --// do not modify
    set nocount on; 
    
    if  (   isnull(parsename(@TableName, 1), '') = '' or
            isnull(parsename(@TableName, 2), '') = ''
        )
    begin
        raiserror('@TableName should be in form of owner.object (dbo.Yak). Cannot continue.', 16, 1, @TableName);
        return;
    end
    if object_id(@TableName) is null
    begin
        raiserror('Table [%s] not found. Cannot continue.', 16, 1, @TableName);
        return;
    end
    if objectproperty(object_id(@TableName), N'TableHasPrimaryKey') = 0
    begin
        raiserror('Table [%s] has no primary key defined. Cannot continue.', 16, 1, @TableName);
        return;
    end
    
    declare @output varchar(max)='', @return int, @sql varchar(max) = '', @list varchar(max) = '', @exec nvarchar(max), @Cols varchar(max)='',
            @sCols varchar(max)='', @aCols varchar(max)='', @pCols varchar(max)='', @uCols varchar(max)='', 
            @b char(1) = char(13), @t char(1) = char(9);
    
    select  @exec = isnull(@exec + '+' + @b,'') + ''','' +' +
            case 
                when c.data_type in ('uniqueidentifier') 
                    then @t + '''''+isnull('''''''' + convert(varchar(50),' + c.column_name + ') + '''''''',''null'')'
                when c.data_type in ('xml') 
                    then @t + '''''+isnull('''''''' + convert(varchar(max),' + c.column_name + ') + '''''''',''null'')'
                when c.data_type in ('char', 'nchar', 'varchar', 'nvarchar', 'sysname') 
                    then @t + '''''+isnull('''''''' + replace(' + c.column_name + ','''''''','''''''''''') + '''''''',''null'')'
                when c.data_type in ('datetime', 'date') 
                    then @t + '''''+isnull('''''''' + convert(varchar,' + c.column_name + ',121)+'''''''',''null'') '
                when c.data_type in ('tinyint', 'int', 'float', 'numeric', 'decimal', 'smallmoney', 'money', 'bit', 'smallint', 'real', 'bigint') 
                    then @t + '''''+isnull(convert(varchar,' + c.column_name + '),''null'')' 
                else ''' ** data type [' + c.data_type + '] not supported **'''
            end,
            @Cols = @Cols + ','+quotename(c.column_name, '['),
            @sCols = @sCols + ',s.'+quotename(c.column_name, '[')
    from    information_schema.columns c
    where   c.table_name = parsename(@TableName, 1) and
            c.table_schema = parsename(@TableName, 2)
    order 
    by      c.ordinal_position
    
    -- stage primary key columns
    declare @pks table (c varchar(100), o int);
    insert into @pks (c,o)
        select  kcu.column_name, kcu.ordinal_position
        from    information_schema.table_constraints tc
        join    information_schema.key_column_usage kcu on
                tc.table_name = kcu.table_name and
                tc.constraint_name = kcu.constraint_name
        where   tc.table_name = parsename(@TableName, 1) and
                tc.table_schema = parsename(@TableName, 2) and
                tc.constraint_type = 'PRIMARY KEY';
       
    -- build primary key columns (1=1 to ease support of composite PKs)
    set @pCols = '1=1'           
    select  @pCols = @pCols + ' and '+isnull('t.'+quotename(c, '[') + ' = ' + 's.'+quotename(c, '['), '')
    from    @pks    
    order
    by      o;
    
    -- build update columns, do not update identities or pks
    select  @aCols = @aCols + ','+quotename(c.[name], '[') + ' = s.' + quotename(c.[name], '[')
    from    sys.columns c
    where   object_id = object_id(@TableName) and
            [name] not in (select c from @pks) and
            columnproperty(object_id(@TableName), c.[name], 'IsIdentity ') = 0;
    
    -- script the data out as table value constructors
    select  @exec = 'set nocount on; Select ' + @b + '''(' + ''' + ' + @b + stuff(@exec,1, 3, '') + '+'')''' + @b + 'from ' + @TableName,
            @Cols = stuff(@Cols,1, 1, ''),
            @sCols = stuff(@sCols,1, 1, ''),
            @aCols = stuff(@aCols,1, 1, '');
            
    declare @tab table (val varchar(max));
    declare @Values varchar(max);
    insert into @tab
        exec(@exec);
    
    if not exists(select 1 from @tab)
    begin
        raiserror('Table %s is valid but empty. Populate it before running this helper.', 16, 1, @TableName);
        return
    end
    
    select @Values = stuff(cast((select ','+ @b + val from @tab for xml path('')) as xml).value('.', 'varchar(max)'),1,2,'');
    
    -- build the merge statement
    set @output +=  @b+'--'+@TableName+replicate('-', 98-len(@TableName))+@b+replicate('-', 100)+@b;
    set @output +=  'set nocount on;'+@b
    if objectproperty(object_id(@TableName), 'TableHasIdentity') = 1 
        set @output += 'set identity_insert ['+parsename(@TableName, 2)+'].[' + parsename(@TableName, 1) + '] on;'+@b;
    set @output +=  ';with cte_data('+@Cols+')'+@b+'as (select * from (values'+@b+'--'+replicate('/', 98) + @b +@Values+ @b +'--'+replicate('\', 98)+ @b +')c('+@Cols+'))'+@b;
    set @output +=  'merge' + @t + '['+parsename(@TableName, 2)+'].[' + parsename(@TableName, 1) + '] as t' + @b + 'using' + @t + 'cte_data as s'+@b;
    set @output +=  'on' + replicate(@t, 2) + @pCols+@b;
    set @output +=  'when matched then' + @b+@t + 'update set'+ @b+@t + @aCols+@b;
    set @output +=  'when not matched by target then'+@b;
    set @output +=  @t+'insert(' + @Cols + ')'+@b;
    set @output +=  @t+'values(' + @sCols + ')'+@b;
    set @output +=  'when not matched by source then' + @b+@t+ 'delete;'+@b;
    if objectproperty(object_id(@TableName), 'TableHasIdentity') = 1 
        set @output += 'set identity_insert ['+parsename(@TableName, 2)+'].[' + parsename(@TableName, 1) + '] off;'
    
    --output the statement as xml (to overcome mgmt studio limitations)
    select s as [output] from (select @output)d(s) for xml path('');
    return;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

So I have this SQL table that I need to update. Now we use
I have 3 tables. Table A contains the data that my query is going
We have a view that is used to lookup a record in a table
I have a lookup table that contains these columns: id, name, value, colx, coly
I have read that enabling Change Data Capture obviously has an impact on database
I have a lookup table called metadata_types in my database, which lists all the
Let's say I have a lookup table which I'd like to make accessible to
I am trying to code a global lookup table of sorts. I have game
I have many tables that use Lookup/Enum references for most of their column values.
I have table with around 70 000 rows. There is 6000 rows that i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.