Clausmeyer (jc*@charite.de ) writes:
thanks for replying,
I'm a bit confused now. Both my docs and the errormessage I get
tell me, that it is allowed to call functions and extended procs from
a function.
sp_executesql is an extended proc, or am I wrong?
Maybe it is. It is still not permitted, and for a very good reason.
the function itself is called from a rather complex select-statement.
It shall take 2 params identifying row and column of a fixed table,
build a select-statement and return the selected value.
simplified code below:
And if your dynamic SQL had performed updates or deletes on the
tables involved in the querey, what had you expected to happen?
As for the problem, what's wrong with:
SELECT @retval = CASE @column
WHEN 'col1' THEN col1
WHEN 'col2' THEN col2
...
END
FROM tbl
WHERE rowid = @rowid
However, I like to add a few more comments.
1) Beware that UDF can severly affect your performance, since the query
might be in practice be converted to a cursor begind the scenes.
2) The fact that want to do such a thing, indicates that your data
model is flawed. Maybe the column names you pass into the query
should have been key values in a table with a two-column key (@rowid,
@column)
3) Beware that if an error occurs in a user-defined function, there is
no way to catch it. The statement that calls the UDF will be terminated,
but @@error will be 0, so you don't if things well or not. Had your
dynamic SQL solution been possible, and you had feed it a invalid
column name, you would not have known.
4) 'select ' + @Column + ' from t_OPs where [Id] = ' +
convert(varchar (20), @RowId) is better written:
SELECT @sql = 'select ' + @Column + ' from t_OPs where [Id] =
convert(varchar (20), @RowId)
EXEC sp_executesql @sql, N'int @RowId', @RowId = @RowId
--
Erland Sommarskog, SQL Server MVP,
es****@sommarsk og.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp