Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come posso copiare tutti i campi di una tabella in un'altra tabella più ampia in SQL Server 2005 Express?

Quindi puoi usare SQL dinamico in questo modo...

DECLARE
    @Fields nvarchar(Max),
    @SQL nvarchar(Max);

SELECT
    @Fields = COALESCE(@Fields + ',', '') + column_name
FROM
    information_schema.columns
WHERE
    table_schema = 'dbo' AND
    table_name = 'Instance' AND
    column_name <> 'PrimaryKeyID' --here you exclude columns
ORDER BY
    ordinal_position;


SET @SQL = 'INSERT INTO dbo.Instance' 
    + ' ('
    + @Fields
    + ') SELECT '
    + ' ('
    + @Fields
    + ') FROM Template;'            

EXECUTE sp_executesql @SQL;