I have a case when I need to translate (search) several values โโfrom one table. The first way I wrote this is to use 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
Since I often use this subquery (that is, I have about 50 tables with these fields), and I might need to add some more code to the subquery (for example, "AND active = 1"), I thought that put them in a user-defined function UDF and use this. But the performance using this UDF was terrible.
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 # 1 is less than 1 second. Productivity No. 2 is about 30 seconds ...
Why, or more importantly, is there a way I can code in SQL Server 2008 so I don't have to use so many subqueries?
Edit:
Just a little more explanation of when this is helpful. This simple request (i.e. get userid) becomes much more complicated when I want to get text for the user, since I need to combine with the profile to get the language, with the company to see if the language should be selected. 'from there instead and with a translation table to get the translated text. And for most of these requests, performance is a minor issue for readability and serviceability.
performance sql sql-server sql-server-2008 user-defined-functions
devzero Feb 04 '09 at 10:01 2009-02-04 10:01
source share