I have a requirement where i need to add multiple columns from a source table after checking existence of those columns. for eg:
Table1 containg 7 coulmns like A, B, C, D, E, F, G and Table2 containing 4 columns like A, B, C, D
I want to check the existency of table1 columns in Table2 and if not exists then add rest 3 columns in Table2. I am looking for a solution where i don't need to add these columns manually if not exists in table2.
How can i do this?
I have tried this:
if exists (SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='table1' and COLUMN_NAME in('A','B','C','D','E','F','G'))
BEGIN
ALTER TABLE table2
ADD [E] FLOAT null
,[F] FLOAT null
,[G] FLOAT null
END;
But this is not the solution of my query I want to make it dynamic and don't know how to do this.
I don't, for one second, think this is a good idea, but this would achieve what you are after. Note that if the same column exists by name in both tables, but have different data types, the column will be ignored:
CREATE TABLE Table1 (a int,
b numeric(12,2),
c datetime2(0),
d date,
e varchar(20),
f sysname,
g varbinary);
CREATE TABLE Table2 (a int,
b numeric(12,2),
c datetime2(0),
d date);
GO
DECLARE @SQL nvarchar(MAX);
SET @SQL = STUFF((SELECT NCHAR(13) + NCHAR(10) +
N'ALTER TABLE Table2 ADD ' + QUOTENAME(T1.name) + N' ' + T1.system_type_name + N';'
FROM sys.dm_exec_describe_first_result_set(N'SELECT * FROM Table1',NULL, NULL) T1
WHERE NOT EXISTS(SELECT 1
FROM sys.dm_exec_describe_first_result_set(N'SELECT * FROM Table2',NULL, NULL) T2
WHERE T1.[name] = T2.[name])
ORDER BY T1.column_ordinal
FOR XML PATH(N''),TYPE).value('.','nvarchar(MAX)'),1,2,N'');
PRINT @SQL;
EXEC sp_executesql @SQL;
GO
SELECT *
FROM dbo.Table2;
GO
DROP TABLE dbo.Table2;
DROP TABLE dbo.Table1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.