Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 exec statement from Function or alternate way

Author  Topic 

j-in-nz
Starting Member

17 Posts

Posted - 2007-03-18 : 22:44:48

I have a function that does various checks, from that function I need to have a select statement which passes the field
name as a parameter to a stored proc. The sp works fine but when I execute it from inside my function i get an error.
So I thought of changing my sp to a function inorder to call a function in a function.
This was my select statement in my sp, this does not work in my function.How do i have an exec statement in a function?
exec ('Select ' + @fieldname + ' from AnnualSetup where Year = ' + @Year)

I have to have it in quotes cos @Fieldname is a column name.

thanks

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2007-03-18 : 22:48:55
Basically you can't. You can't use exec() in a function. You have to use Stored Procedure instead


KH

Go to Top of Page

j-in-nz
Starting Member

17 Posts

Posted - 2007-03-19 : 04:00:38
Unfortunately I cannot change this to a stored proc, cos the function which calls it is pretty big and can't change that. Is there another way I can
'Select @col name from Table1' in a function where @col is a column name therefore requires the single quote as per original forum
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-03-19 : 04:03:05
Use Multiple IF's.

If @ColName = 'Col1'
SELECT Col1 FROM Table WHERE Year = @Year

If @ColName = 'Col2'
SELECT Col2 FROM Table WHERE Year = @Year


Peter Larsson
Helsingborg, Sweden
Go to Top of Page
   

- Advertisement -