How to add multiple columns from another table in sql server 2017? - sql

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;

Related

SQL copying record with out specifying column list; ignoring Identity

I'm trying to copy a record from TableA back to TableA, but using a new Identity.
I don't want to specify column list as I have over 100 columns, and there may be more in the future. Id like a chunk of code that can run when/if things change.
After looking similar questions, I have attempted this code
SELECT * INTO #tmp FROM TableA WHERE Id = 1;
ALTER TABLE #tmp DROP COLUMN Id;
INSERT INTO TableA SELECT * FROM #tmp;
Drop Table #tmp;
I am however still getting this error
An explicit value for the identity column in table 'dbo.TableA' can only be specified when a column list is used and IDENTITY_INSERT is ON.
Running a Select * FROM #tmp gives me what I would expect. A single record with all my Columns with the exception of the Id column.
Any Ideas?
Thanks!
EDIT
Here is a pictures of the properties of the Id Column
Use Dynamic SQL: get your list of columns (except ID), build an insert statement using that list, and then call exec on it:
SELECT *
INTO #tmp
FROM TableA
WHERE Id = 1;
ALTER TABLE #tmp DROP COLUMN id;
DECLARE #cols varchar(max);
SELECT
#cols = COALESCE(#cols + ',', '') + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TableA' AND COLUMN_NAME <> 'id'
--select #cols -- display column list for debugging
DECLARE #sqltxt varchar(max) = 'INSERT INTO TableA (' + #cols + ') SELECT * FROM #tmp';
--SELECT #sqltxt -- display the statement for debugging
exec (#sqltxt)
DROP TABLE #tmp
Try This
Step 1 :
INSERT INTO Employee1(FirstName,LastName,ManagerID,Salary)
SELECT FirstName,LastName,ManagerID,Salary
FROM Employee1
WHERE EmployeeID=X -- Your Emplyee ID
Step 2:
DELETE FROM Employee1 WHERE EmployeeID=X

Create a Table based on a list from another table

I have compiled a list of columns which I hope to build a table with. Is it possible to use a procedure to create a table based on this list? Ie
List
A
B
C
New_Table
Column A Column B Column C
Customer is atable consist of column List with rows:- A, B, C
What I've done is added a RowNum column on run time into the customer table which is dynamic. Due to this another column of row number got attached with List column. Using this:-
RowNum=1 provides A
RowNum=2 provides B
RowNum=3 provides C
Here is the procedure as per your requirement. Please verify:-
create procedure newtable
#tablename NVARCHAR(1000)
as
Declare #col1 varchar(50),#col2 varchar(50),#col3 varchar(50), #cmd NVARCHAR(1000)
select #col1=List from (select List,ROW_NUMBER() Over(Order by List) as RowNum from customer)x where x.RowNum=1
select #col2=List from (select List,ROW_NUMBER() Over(Order by List) as RowNum from customer)x where x.RowNum=2
select #col3=List from (select List,ROW_NUMBER() Over(Order by List) as RowNum from customer)x where x.RowNum=3
set #cmd=N'Create Table '+#tablename+ N' (' + #col1+N' Varchar(50),'+#col2 + N' varchar(50),'+#col3+N' varchar(50))' ;
print #cmd
Exec(#cmd)
After this run your command:-
exec newtable 'New_table'

Rename columns in 1 table to row values in another table

Ok, so I have 2 tables in all:
Table 1 has these 3 columns which are not meaningful as they are just a varchar value:
Q19243 Q19244 Q19245
Table 2 has 2 columns ColumnName and TextValue.
ColumnName holds the values of the name of the 3 columns in Table 1 (Q19243 etc) and also has a corresponding column called TextValue which holds a friendly description of what Q19243 actually means.
So there are 3 records in Table 2, 1 for each column in Table 1.
I would like to rename these 3 columns in Table 1 to equal whatever is in the TextValue column in Table 2. I would like to do this dynamically rather than a simple UPDATE statement to rename the columns. Sorry I did not attach screen shots but I do not see an attach button to do so...
If you run this code to create an example of the 2 tables then you should probably have a better idea of what I'm referring to.
create table #Table1 (Q19243 varchar(10),Q19244 varchar(10),Q19245 varchar(10))
Create table #Table2 (ColumnName varchar(10),TextValue varchar(50))
Insert into #Table2 select 'Q19243','Provider Name'
Insert into #Table2 select 'Q19244','The Provider You Usually See'
Insert into #Table2 select 'Q19245','How Long Going to Provider'
select * from #Table1
select * from #Table2
drop table #Table1
drop table #Table2
Since the purpose of the column rename is for output purposes only, you can use a query against Table2 to create Dynamic SQL specific to Table1 that aliases the column names on the SELECT.
(the following example uses the sample code in the original question and only differs by what is between the --============== lines)
create table #Table1 (Q19243 varchar(10),Q19244 varchar(10),Q19245 varchar(10))
Create table #Table2 (ColumnName nvarchar(10),TextValue nvarchar(50))
Insert into #Table2 select 'Q19243','Provider Name'
Insert into #Table2 select 'Q19244','The Provider You Usually See'
Insert into #Table2 select 'Q19245','How Long Going to Provider'
select * from #Table1
select * from #Table2
--=========================================
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = COALESCE(#SQL + N',', N'SELECT')
+ N' t1.'
+ t2.ColumnName
+ N' AS ['
+ t2.TextValue
+ N']'
FROM #Table2 t2
SET #SQL = #SQL + N' FROM #Table1 t1'
SELECT #SQL
EXEC(#SQL)
--=========================================
drop table #Table1
drop table #Table2
The value of #SQL after the SELECT #SQL= query is:
SELECT t1.Q19243 AS [Provider Name], t1.Q19244 AS [The Provider You
Usually See], t1.Q19245 AS [How Long Going to Provider] FROM #Table1
t1
Note: you need the square-brackets around the field name alias (value from Table2.TextValue) as there are spaces in the string.

SELECT INTO behavior and the IDENTITY property

I've been working on a project and came across some interesting behavior when using SELECT INTO. If I have a table with a column defined as int identity(1,1) not null and use SELECT INTO to copy it, the new table will retain the IDENTITY property unless there is a join involved. If there is a join, then the same column on the new table is defined simply as int not null.
Here is a script that you can run to reproduce the behavior:
CREATE TABLE People (Id INT IDENTITY(1,1) not null, Name VARCHAR(10))
CREATE TABLE ReverseNames (Name varchar(10), ReverseName varchar(10))
INSERT INTO People (Name)
VALUES ('John'), ('Jamie'), ('Joe'), ('Jenna')
INSERT INTO ReverseNames (Name, ReverseName)
VALUES ('John','nhoJ'), ('Jamie','eimaJ'), ('Joe','eoJ'), ('Jenna','anneJ')
--------
SELECT Id, Name
INTO People_ExactCopy
FROM People
SELECT Id, ReverseName as Name
INTO People_WithJoin
FROM People
JOIN ReverseNames
ON People.Name = ReverseNames.Name
SELECT Id, (SELECT ReverseName FROM ReverseNames WHERE Name = People.Name) as Name
INTO People_WithSubSelect
FROM People
--------
SELECT OBJECT_NAME(c.object_id) as [Table],
c.is_identity as [Id Column Retained Identity]
FROM sys.columns c
where
OBJECT_NAME(c.object_id) IN ('People_ExactCopy','People_WithJoin','People_WithSubSelect')
AND c.name = 'Id'
--------
DROP TABLE People
DROP TABLE People_ExactCopy
DROP TABLE People_WithJoin
DROP TABLE People_WithSubSelect
DROP TABLE ReverseNames
I noticed that the execution plans for both the WithJoin and WithSubSelect queries contained one join operator. I'm not sure if one will be significantly better on performance if we were dealing with a larger set of rows.
Can anyone shed any light on this and tell me if there is a way to utilize SELECT INTO with joins and still preserve the IDENTITY property?
From Microsoft:
When an existing identity column is
selected into a new table, the new
column inherits the IDENTITY property,
unless one of the following conditions
is true:
The SELECT statement contains a join, GROUP BY clause, or aggregate function.
Multiple SELECT statements are joined by using UNION.
The identity column is listed more than one time in the select list.
The identity column is part of an expression.
The identity column is from a remote data source.
If any one of these conditions is
true, the column is created NOT NULL
instead of inheriting the IDENTITY
property. If an identity column is
required in the new table but such a
column is not available, or you want a
seed or increment value that is
different than the source identity
column, define the column in the
select list using the IDENTITY
function.
You could use the IDENTITY function as they suggest and omit the IDENTITY column, but then you would lose the values, as the IDENTITY function would generate new values and I don't think that those are easily determinable, even with ORDER BY.
I don't believe there is much you can do, except build your CREATE TABLE statements manually, SET IDENTITY_INSERT ON, insert the existing values, then SET IDENTITY_INSERT OFF. Yes you lose the benefits of SELECT INTO, but unless your tables are huge and you are doing this a lot, [shrug]. This is not fun of course, and it's not as pretty or simple as SELECT INTO, but you can do it somewhat programmatically, assuming two tables, one having a simple identity (1,1), and a simple INNER JOIN:
SET NOCOUNT ON;
DECLARE
#NewTable SYSNAME = N'dbo.People_ExactCopy',
#JoinCondition NVARCHAR(255) = N' ON p.Name = r.Name';
DECLARE
#cols TABLE(t SYSNAME, c SYSNAME, p CHAR(1));
INSERT #cols SELECT N'dbo.People', N'Id', 'p'
UNION ALL SELECT N'dbo.ReverseNames', N'Name', 'r';
DECLARE #sql NVARCHAR(MAX) = N'CREATE TABLE ' + #NewTable + '
(
';
SELECT #sql += c.name + ' ' + t.name
+ CASE WHEN t.name LIKE '%char' THEN
'(' + CASE WHEN c.max_length = -1
THEN 'MAX' ELSE RTRIM(c.max_length/
(CASE WHEN t.name LIKE 'n%' THEN 2 ELSE 1 END)) END
+ ')' ELSE '' END
+ CASE c.is_identity
WHEN 1 THEN ' IDENTITY(1,1)'
ELSE ' ' END + ',
'
FROM sys.columns AS c
INNER JOIN #cols AS cols
ON c.object_id = OBJECT_ID(cols.t)
INNER JOIN sys.types AS t
ON c.system_type_id = t.system_type_id
AND c.name = cols.c;
SET #sql = LEFT(#sql, LEN(#sql)-1) + '
);
SET IDENTITY_INSERT ' + #NewTable + ' ON;
INSERT ' + #NewTable + '(';
SELECT #sql += c + ',' FROM #cols;
SET #sql = LEFT(#sql, LEN(#sql)-1) + ')
SELECT ';
SELECT #sql += p + '.' + c + ',' FROM #cols;
SET #sql = LEFT(#sql, LEN(#sql)-1) + '
FROM ';
SELECT #sql += t + ' AS ' + p + '
INNER JOIN ' FROM (SELECT DISTINCT
t,p FROM #cols) AS x;
SET #sql = LEFT(#sql, LEN(#sql)-10)
+ #JoinCondition + ';
SET IDENTITY_INSERT ' + #NewTable + ' OFF;';
PRINT #sql;
With the tables given above, this produces the following, which you could pass to EXEC sp_executeSQL instead of PRINT:
CREATE TABLE dbo.People_ExactCopy
(
Id int IDENTITY(1,1),
Name varchar(10)
);
SET IDENTITY_INSERT dbo.People_ExactCopy ON;
INSERT dbo.People_ExactCopy(Id,Name)
SELECT p.Id,r.Name
FROM dbo.People AS p
INNER JOIN dbo.ReverseNames AS r
ON p.Name = r.Name;
SET IDENTITY_INSERT dbo.People_ExactCopy OFF;
I did not deal with other complexities such as DECIMAL columns or other columns that have parameters such as max_length, nor did I deal with nullability, but these things wouldn't be hard to add it if you need greater flexibility.
In the next version of SQL Server (code-named "Denali") you should be able to construct a CREATE TABLE statement much easier using the new metadata discovery functions - which do much of the grunt work for you in terms of specifying precision/scale/length, dealing with MAX, etc. You still have to manually create indexes and constraints; but you don't get those with SELECT INTO either.
What we really need is DDL that allows you to say something like "CREATE TABLE a IDENTICAL TO b;" or "CREATE TABLE a BASED ON b;"... it's been asked for here, but has been rejected (this is about copying a table to another schema, but the same concept could apply to a new table in the same schema with a different table name). http://connect.microsoft.com/SQLServer/feedback/details/632689
I realize this is a really late response but whoever is still looking for this solution, like I was until I found this solution:
You can't use the JOIN operator for the IDENTITY column property to be inherited.
What you can do is use a WHERE clause like this:
SELECT a.*
INTO NewTable
FROM
MyTable a
WHERE
EXISTS (SELECT 1 FROM SecondTable b WHERE b.ID = a.ID)
This works.

In SQL Server, how can I compare rows using the column names from another table

I have two tables A and B, with dynamic columns where I have no idea what columns are key inside them, except from another table called C.
The C table specifies which column/s is a key column in tables A and B. There can be 1 or more key columns.
My question is, how would I generate such a query where I select all rows from A where the key columns are equal to the same key columns in B?
One idea I had was to create a text query that I execute with sp_executesql, but I need some good ideas on how to generate the query.
First of all, I would select all key columns from table C for the table A and B to my declared table #keyColumns.
Then I would use a while loop to go through all key columns inside #keyColumns and generate the query and execute it with sp_executesql.
For example:
UPDATE A
SET ...
FROM B INNER JOIN A
ON A.keycol1 = B.keycol1 AND A.keycol2 = B.keycol2 AND ...
Just to make it clear, the C table only specifies key columns for the table B, and from that I know A has the same key columns.
But I want to know if there's a better way to solve this.
Are the key columns held in 'C' the primary key? If so you can retrieve these from INFORMATION_SCHEMA.TABLE_CONSTRAINTS, and INFORMATION_SCHEMA.KEY_COLUMN_USAGE as described here rather than using a different table.
You have to use dynamic SQL for this I think. There is no syntax like FROM B JOIN A ON PRIMARY KEYS. Instead of the WHILE loop though you can just concatenate your query through a SELECT as below.
DECLARE #DynSql nvarchar(max)
DECLARE #TableA sysname
DECLARE #TableB sysname
SET #TableA = 'A'
SET #TableB = 'B';
WITH C AS
(
SELECT 'B' AS [Table], 'keycol2' As col UNION ALL
SELECT 'B' AS [Table], 'keycol1' As col UNION ALL
SELECT 'X' AS [Table], 'keycol1' As col
)
SELECT #DynSql = ISNULL(#DynSql + ' AND ','')+ #TableA + '.'+QUOTENAME(col) + '= ' + #TableB + '.'+QUOTENAME(col)
FROM C WHERE [Table] = #TableB
IF ##ROWCOUNT=0
RAISERROR('No Entry found for table %s',16,1,#TableB)
SET #DynSql =
'UPDATE ' + #TableA + '
SET ...
FROM ' + #TableB + ' INNER JOIN ' + #TableA + ' ON
' + #DynSql
PRINT #DynSql