Groups | Blog | Home
all groups > sql server programming > april 2004 >

sql server programming : Scalar Result from Non-existing table needed


Senad Ljuca
4/10/2004 10:19:57 PM
Is there any way to generate artificial Query Result from Non-existing
table, as scalar array needed for another Query?

For Example:
There is one Table tbl1 with the Field f1, and appropriate Values v1, v2,
v3,
Therefore, a Query SELECT f1 FROM tbl1 gives the following:
f1
--
v1
v2
v3
....

What I need is the following Result:
f1, f2
-----
v1, 1
v1, 2
v1, 3
v1, 4
v2, 1
v2, 2
....

therefore I need some artificial Table with one int field and 4 Records: 1,
2, 3, 4, then could I with CROSS JOIN query statement acchieve the goal.

I would appreciate any suggestion



Best Regards, Senad




Karl Gram
4/10/2004 10:31:49 PM
Hi Senda,

One solution is to use a table valued function:

create function ufn_number (@size int)
returns @tbl table (number int)
as
begin
while @size > 0
begin
insert into @tbl(number) values (@size)

set @size = @size - 1
end

return
end
go


Call this function as a normal table like with a parameter to determine the
size:

select number from ufn_number(4)

or in your case:

SELECT f1, number
FROM tbl1 CROSS JOIN ufn_number(4)


--
Karl Gram, BSc, MBA
http://www.gramonline.com


[quoted text, click to view]

Senad Ljuca
4/10/2004 10:42:03 PM
Hallo Karl,

Very nice solution, thank you very much

"Karl Gram" <NOSPAMkarl@gramonline.nl> schrieb im Newsbeitrag
news:uQI$7pzHEHA.1220@tk2msftngp13.phx.gbl...
[quoted text, click to view]

Hugo Kornelis
4/10/2004 11:23:22 PM
[quoted text, click to view]

As an alternative to Karl's function, you could also use UNION to
create the non-existing table as a derived table:

select tbl1.f1,tbl2.f2
from tbl1
cross join (select 1 AS f2
union select 2
union select 3
union select 4) AS tbl2


Best, Hugo
--

Senad Ljuca
4/11/2004 12:46:23 AM
Hi Hugo,

Thanks for your support. I have compared the two solutions. Both of them
function correctly, the one with the function seems to be about 10% quicker
(even as quick as with the static Table in the Database!)

Best Regards

Senad


"Hugo Kornelis" <hugo@pe_NO_rFact.in_SPAM_fo> schrieb im Newsbeitrag
news:ccpg7017hiuisigk11mhv4c25ilg5j5dqg@4ax.com...
[quoted text, click to view]

Karl Gram
4/12/2004 10:28:42 PM
Hi Senad,

Try it with a union all instead of a union and you should see that this
solution should perform better...

select 1 AS f2
union all select 2
union all select 3
union all select 4

The reason is that a UNION will try to remove duplicates from the resultset
and therefore needs more processing logic. A UNION ALL just concatenates all
the resultsets it gets. Look at the execution plans to see the
difference....

--
Karl Gram, BSc, MBA
http://www.gramonline.com


[quoted text, click to view]

AddThis Social Bookmark Button