I have a case where i need to translate (lookup) several values from the same table. First way I wrote it, was using subqueries:
SELECT
(SELECT id FROM user WHERE user_pk = created_by) AS creator,
(SELECT id FROM user WHERE user_pk = updated_by) AS updater,
(SELECT id FROM user WHERE user_pk = owned_by) AS owner,
[name]
FROM asset
As I'm using this subquery a lot (ie I have about 50 tables with these fields), and I might need to add some more code to the subquery (f.eks "AND active = 1" ) I thougth id put these into a UDF and use that. But the performance using that UDF was abysmal.
CREATE FUNCTION dbo.get_user ( @user_pk INT )
RETURNS INT
AS BEGIN
RETURN ( SELECT id
FROM ice.dbo.[user]
WHERE user_pk = @user_pk )
END
SELECT dbo.get_user(created_by) as creator, [name]
FROM asset
Performance of #1 is less than 1 sec. Performance of #2 is about 30 seconds...
Could anyone explain to me why, or more importantly, is there anyway I can code in SQL server 2008 so that I don't have to use so many subqueries?
edit:
just a litte more explanation of when this is usefull. This simple querey (ie get userid) gets a lot more complex when I want to have a tekst for a user, since I have to join with profile to get language, with company to see if language should be fetch'ed from there instead, and with the translation table to get the translated text. And for most of these queries, performance is a secondary issue to read/maintainability.