Cartesian Product SQL / Inserts with multiple Values Clauses
-
16-10-2019 - |
Question
I want to create cartesian product sql query.But,I'm getting the error.Where I wrong?
alter table #Personel
(
Ad varchar(100)
)
alter table #Masa
(
MasaAdi varchar(100)
)
insert into #Personel values('deneme1'),('deneme2'),('deneme3')
insert into #Masa values('Masa1'),('masa2'),('masa3')
select Ad,MasaAdi from
(
select ROW_NUMBER() over(partition by MasaAdi order by ID,Ad ) as Sira
,ID,Ad,MasaAdi
from (
select newid() as ID,Ad,MasaAdi from #Personel
left outer join #Masa on 1=1
) t
) t2 where Sira = 1 order by Ad
Solution
On SQL Server you can write
select Ad,MasaAdi from
(
select ROW_NUMBER() over(partition by MasaAdi order by ID,Ad ) as Sira,ID,Ad,MasaAdi
from (
select newid() as ID,Ad,MasaAdi
from #Personel
cross join #Masa
)t
) t2 where Sira = 1 order by Ad
This is the best syntax to emphasize that it is a cross join.
But on SQL Server 2008 your query gives the same result .
EDIT:
Your problem is not the select statement, but the inserts. Inserts with multiple value clauses is a new feature of SQL Server 2008. For 2005 you have to write:
insert into #Personel values('deneme1')
insert into #Personel values('deneme2')
insert into #Personel values('deneme3')
insert into #Masa values('Masa1')
insert into #Masa values('masa2')
insert into #Masa values('masa3')
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange