December 15, 2016 at 8:10 am
How can I insert into a new table (Table 3) The example below:
Table 1 -
Column1
Texas
Oklahoma
Table 2 -
Column1
1
2
Table 3:
Column1 Column2
Texas 1
Texas 2
Oklahoma 1
Oklahoma 2
Thanks,
Baze
December 15, 2016 at 8:27 am
Use INSERT INTO...SELECT...
And use a cross join to get the expected result.
December 15, 2016 at 8:27 am
SELECT *
INTO Table3
FROM Table1 CROSS JOIN Table2
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
December 15, 2016 at 8:27 am
what you are looking for is a Cartesian Product;
also known as a cross join
the syntax is pretty simple:
SELECT * FROM #Table1
CROSS JOIN #Table2
in the future, if you want the best help, put code in place that actually creates and populates your sample tables; then anyone can copy paste your sample,and come up with a tested , working solution for whatever problem you present.
here's a full example:
IF OBJECT_ID('tempdb.[dbo].[#Table1]') IS NOT NULL
DROP TABLE [dbo].[#Table1]
GO
CREATE TABLE #Table1(Column1 VARCHAR(30) )
INSERT INTO #Table1
VALUES('Texas'),('Oklahoma')
IF OBJECT_ID('tempdb.[dbo].[#Table2]') IS NOT NULL
DROP TABLE [dbo].[#Table2]
GO
CREATE TABLE #Table2(Column1 int )
INSERT INTO #Table2
VALUES(1),(2)
SELECT * FROM #Table1
CROSS JOIN #Table2
Lowell
December 15, 2016 at 8:30 am
cboese (12/15/2016)
How can I insert into a new table (Table 3) The example below:Table 1 -
Column1
Texas
Oklahoma
Table 2 -
Column1
1
2
Table 3:
Column1 Column2
Texas 1
Texas 2
Oklahoma 1
Oklahoma 2
Thanks,
Baze
If Table3 doesn't already exist, use SELECT/INTO with a CROSS JOIN.
SELECT Column1 = t1.Column1
,Column2 = t2.Column1
INTO dbo.Table2
FROM dbo.Table1 t1
CROSS JOIN dbo.Table2 t2
;
If Table3 already exists, then change the query into an INSERT/SELECT with the same CROSS JOIN.
INSERT INTO dbo.Table3
(Column1, Column2)
SELECT Column1 = t1.Column1
,Column2 = t2.Column1
FROM dbo.Table1 t1
CROSS JOIN dbo.Table2 t2
;
{EDIT} Went from 0 replies to all those in the time it took me to type my answer.
--Jeff Moden
Change is inevitable... Change for the better is not.
December 15, 2016 at 8:58 am
Jeff Moden (12/15/2016)
{EDIT} Went from 0 replies to all those in the time it took me to type my answer.
Gail, Lowell and I posted almost at the same time. I was going to edit my answer, but they had already given better answers.
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply