Search
 
SCRIPT & CODE EXAMPLE
 

SQL

update all columns in one update

--Procedure to Update all columns in a given table (@Source) w/ Join from another Table (@Dest)
    CREATE PROCEDURE UPDATE_ALL

    @SOURCE VARCHAR(100),
    @DEST VARCHAR(100),
    @ID VARCHAR(100)

    AS

        DECLARE @SQL VARCHAR(MAX) =  

        'UPDATE D SET ' +

        -- Google 'for xml path stuff' This gets the rows from query results and 
        -- turns into comma separated list.
        STUFF((SELECT ', D.'+ COLUMN_NAME + ' = S.' + COLUMN_NAME
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = @DEST
        AND COLUMN_NAME <> @ID 
        FOR XML PATH('')),1,1,'')

        + ' FROM ' + @SOURCE + ' S JOIN ' + @DEST + ' D ON S.' +  @ID + ' = D.' + @ID

        --SELECT @SQL
        EXEC (@SQL)
    
    
    
    --usage: 
    	EXEC UPDATE_ALL 'source_table','destination_table','id_column'
    
    
    
   -- Here's a hardcore way to do it with SQL SERVER. Carefully consider security and integrity before you try it, though.
    --This uses schema to get the names of all the columns and then puts together a big update statement to update all columns except ID column, which it uses to join the tables.
    --This only works for a single column key, not composites.

Comment

PREVIOUS NEXT
Code Example
Sql :: update view sql 
Sql :: test connection to sql server 
Sql :: select first and last row mysql 
Sql :: Why mysql is used? 
Sql :: triggers db 
Sql :: mysql split explode 
Sql :: group_concat sql server 
Sql :: how to use sqlcommand 
Sql :: SQL Equal to Operator 
Sql :: sql Not like operator 
Sql :: how to uninstall mysql windows 10 
Sql :: sql Top 5 sutradara dengan filem terbanyak 
Sql :: create-toys-table-with-toy_name-column 
Sql :: sql examples from framework 
Sql :: oracle privileges 
Sql :: sql server set column name as variable 
Sql :: mysql config address 
Sql :: delete double on SQL with multiple primary keys 
Sql :: oracle execute immediate quotes 
Sql :: get start of week big query 
Sql :: sqlite explain plan 
Sql :: AND Operator (AND) 
Sql :: psql limit order group by 
Sql :: mysl like insert a variable 
Sql :: create view in sql server that contain multiple select statements 
Sql :: update all linkedserver tables with openquery on db 
Sql :: tsql default value when no value returned by query 
Sql :: allow null sql 
Sql :: alembic upgrade show sql 
Sql :: jdbc:sqlserver://localhost;username=MyUsername;password={pass";{}}word}; 
ADD CONTENT
Topic
Content
Source link
Name
4+3 =