Quantcast
Channel: Answers for "User defined function query"
Viewing all articles
Browse latest Browse all 8

Answer by Kristen

$
0
0

Yeah, I think that's good. It will be more efficient if you parametrise the WHERE clause:

DECLARE @P_TABLE VARCHAR(50)
DECLARE @P_KEY VARCHAR(5)
DECLARE @MSTR VARCHAR(100)

SET @P_TABLE = 'EMPLOYEE'
SET @P_KEY = '02814'
SET @MSTR = 'SELECT * FROM '+ @P_TABLE+' WHERE EMP_NO=@P_KEY'
exec sp_executesql @MSTR, N'@P_KEY varchar(100)', @P_KEY

You cannot do that with the TABLE parameter, so it needs to be part of the Dynamic SQL String. However, this query SELECT * FROM MyTable WHERE EMP_NO=@P_KEY will be cached, so any subsequent query that is EXACTLY the same will use the cached query plan - regardless of the actual value of @P_KEY. If someone causes another query to be raised for a different table that will be cached too - and the popular ones will remain in the cache.

You should not use SELECT * as that is not efficient, name the columns you want explicitly; this will also prevent you retrieving all columns in the future - e.g. when the table changes to add some massive TEXT column you don't want all the places in the application that use this query retrieving the new columns that the application doesn't use, as that will only slow everything down.


Viewing all articles
Browse latest Browse all 8

Latest Images

Trending Articles





Latest Images