How to transfer data from one table to another - database

I have two tables, I want to transfer all data from the first table to the second table in case of this data is not exits i nthe second table. how to do it using MS-sql server query ?

it could be something like:
INSERT INTO tableB(FieldA, FieldB, FieldC)
SELECT a.FieldA, a.FieldB, a.FieldC
FROM tableA a
WHERE NOT EXISTS
(
SELECT *
FROM tableB b
/* Primary key field(s)*/
WHERE b.FieldA =a.FieldA
)

in ms-sql you could do something like this:
INSERT INTO mytable(column1, column2) select value1, value2 from mytable2;
but you must make sure that the column1 and value1 have the same datatype same with column2.
Hope it helps. ;)

If the table doesn't exixst you can
SELECT * INTO SECOND_TABLE
FROM FIRST_TABLE;
If you want it to run even if table exists you can preceed this query with:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[YOUR_SCHEMA].[SECOND_TABLE]') AND type in (N'U'))
DROP TABLE [YOUR_SCHEMA].[SECOND_TABLE];

Related

Can we use Parameterized Views in Snowflake?

Can we use Parameterized Views in Snowflake. Such as pass the table name or database name as parameters instead of hardcoding it?
I think your best bet is to use session variables in conjunction with a regular view.
A session variable can be referenced in the view DDL, and will need to be set in any sessions querying the view.
To do this, you can make use of the IDENTIFIER function in Snowflake, which lets you use text as an object identifier.
create table t1 (col1 number, col2 number);
create table t2 (col1 number, col2 number);
set ti = 't1';
create view v1 as select col1, col2 from identifier($ti);
Before you query the view, you will need to set the session variable (ti in this case) to the table name (fully qualified if need be).
set ti = 't1';
select * from v1; -- returns data from t1
set ti = 't2';
select * from v1; -- returns data from t2
I have not found a way to do this, so I've created what I call a "wrapper view" in the past when I need something like this, example as follows.
I hope this helps...Rich
--create source tables and test records
CREATE TABLE t1 (id NUMBER, str VARCHAR);
CREATE TABLE t2 (id NUMBER, str VARCHAR);
CREATE TABLE t3 (id NUMBER, str VARCHAR);
INSERT INTO t1 VALUES(1, 'record from t1');
INSERT INTO t1 VALUES(2, 'record from t1');
INSERT INTO t2 VALUES(100, 'record from t2');
INSERT INTO t2 VALUES(101, 'record from t2');
INSERT INTO t3 VALUES(998, 'record from t3');
INSERT INTO t3 VALUES(999, 'record from t3');
--create the "wrapper" view
CREATE VIEW vw_t AS (
SELECT 't1' as table_name, * FROM t1
UNION ALL
SELECT 't2' as table_name, * FROM t2
UNION ALL
SELECT 't3' as table_name, * FROM t3);
--try it out
SELECT *
FROM vw_t
WHERE table_name = 't3';
--results
TABLE_NAME ID STR
t3 998 record from t3
t3 999 record from t3
I think the best way to handle something like this would be to create a UDTF that acts like a view that has been parameterized. So, in essence, you'd reference the UDTF like a view and pass the parameters into the UDTF, which would then return the data that you wish to use. Note that Snowflake has 2 options for UDTF (SQL and Javascript):
https://docs.snowflake.net/manuals/sql-reference/udf-table-functions.html
https://docs.snowflake.net/manuals/sql-reference/udf-js-table-functions.html
Although when using the interactive SQL worksheet on Snowflake, you can do this:
SET target_table_name='myTable';
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=$target_table_name
That does not work programmatically. Instead, as described here, a parameterized query such as a view uses this syntax:
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=(?)
And yes, the name of that first (?) parameter is 1.
I'm working on my SnowflakeSQLHelper (an adaptation of the Microsoft Patterns and Practices) that will help when attaching parameters.

Copy data from one table into another new table where columns are unknown

I'm trying to copy all data from Table1 into Table2.
I don't know what and how many columns are their in table 1. I mean I want to copy even column names from table 1 to table 2.
There is option like
insert *
into #table2
from Table1
but I even can't use this because there are many select query which has already been written at past. So I have to do something like this.
insert *
into #table2
from (select * from Table1)
This is throwing an error
Incorrect syntax near )
Try This:
Select * into #table2 from (select * from table1 ) as X
---To copy along with data..
select * into newtable from oldtable
--to copy only schema..
select * into newtable from oldtable where 1=2

How to get ID from one table and associate with record in another table in SQL Server

I've tried searching for the answer to this one to no avail. There is no good logic behind the way this was setup. The guy does not know what he's doing, but it's what I have to work with (long story).
I'm using SQL Server 2008R2 I need to take records from one table and transfer the data to 4 separate tables all with a one to one relationship (I know - not smart). I need to get the value from the Identity field in the first table the data is inserted into, then populate the other 3 tables with the same ID and disperse the data accordingly. for example:
OldTable: Field1, Field2, Field3, Field4
NewTable1: Identity field, Field1
NewTable2: ID, Field2
NewTable3: ID, Field3
NewTable4: ID, Field4
I'd like to handle this in a stored procedure. I'd like to do a loop, but I read that loops in SQL are inadvisable.
Loop moving through each record in OldTable... (??)
INSERT INTO NewTable1
(Field1)
Select Field1 from OldTable
INSERT INTO NewTable2
(ID, Field2)
Select SCOPE_IDENTITY?, Field2 From OldTable Where OldTable.ID = ??
etc for other 2 tables
Loop to next record in OldTable
I am not sure how to use SCOPE_IDENTITY, but I have a feeling this will be involved in how I accomplish this.
Also, I'm probably going to need to setup a trigger for whenever a new record is created in NewTable1. I know, it's insanity, but I can't do anything about it, just have to work around it.
So, I need to know
1: the best way to initially populate the tables
2: how to make triggers for new records
The solution to 1 might involve 2.
Please help!
You can use the output clause of the merge statement to get a mapping between the existing primary key in OldTable and the newly generated identity ID in NewTable1.
-- Temp table to hold the mapping between OldID and ID
create table #ID
(
OldID int primary key,
ID int
);
-- Add rows to NewTable1 and capture the ID's in #ID
merge NewTable1 as T
using OldTable as S
on 1 = 0
when not matched by target then
insert(Field1) values(S.Field1)
output S.ID, inserted.ID into #ID(OldID, ID);
-- Add rows to NewTable2 using #ID to get the correct value for each row
insert into NewTable2(ID, Field2)
select I.ID, O.Field2
from #ID as I
inner join OldTable as O
on I.OldID = O.ID
insert into NewTable3(ID, Field3)
select I.ID, O.Field3
from #ID as I
inner join OldTable as O
on I.OldID = O.ID
insert into NewTable4(ID, Field4)
select I.ID, O.Field4
from #ID as I
inner join OldTable as O
on I.OldID = O.ID
drop table #ID;
SQL Fiddle
See also Using merge..output to get mapping between source.id and target.id
How about using the OUTPUT clause of the insert statement? Assuming that Field1 is a unique key on the OldTable...
Declare #IDinserted table(ID int, Field1 varchar(255));
Insert Into NewTable1(Field1)
Output inserted.ID, inserted.Field1 into #IDinserted
Select OldID, Field1 from OldTable;
Insert Into NewTable2(RowID, Field2)
Select i.ID, o.#Field2
from #IDinserted i Inner Join OldTable o
on i.Field1=o.Field1;

SELECT INSERT INTO

Is it possible to insert data from select statement into a a dynamically created table? I will not know how many columns are there in select statement until I run the query. It has to create the appropriate number of columns at run time.
Thank you,
Smith
Just use the SELECT INTO syntax:
SELECT *
INTO NewTable
FROM MyTable
WHERE ...
The new table NewTable will be created with the same columns as your select statement.
You can use a CTAS pattern for this
USE AdventureWorks
GO
----Create new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable
GO
Have a look at This Article on CTAS
-- This creates temporary table
select *
into #newtable
from YourTable
select * from #newtable
-- This creates physical table in the DB
select *
into newtable
from YourTable
select * from newtable

How to save select query results within temporary table?

I need to save select query output into temporary table. Then I need to make another select query against this temporary table. Does anybody know how to do it?
I need to make this on SQL Server.
select *
into #TempTable
from SomeTale
select *
from #TempTable
You can also do the following:
CREATE TABLE #TEMPTABLE
(
Column1 type1,
Column2 type2,
Column3 type3
)
INSERT INTO #TEMPTABLE
SELECT ...
SELECT *
FROM #TEMPTABLE ...
DROP TABLE #TEMPTABLE
In Sqlite:
CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;

Resources