1

Im trying to execute a scalar valued function in an insert query. Im using sql parameter collection but still stuck with it.

Query

Insert into PackageProducts values (@id, @name, @prodId, @prodCode)

// I want to call a scalar valued function to get value for the @prodCode when this query excecutes

Function

create function getProdCodeById(@id uniqueidentifier) returns varchar(15)
begin
declare @code varchar(15)
select @code=ProductCode from Products where ID=@id
return @code
end

What I'm trying to do

//create command, connection etc.. after than

DbParameter param = createParameter() ; // returns an empty parameter
param.Name = "@prodCode";
param.Value = String.Format("getProdCodeById('{0}')", 5);

when I execute , it takes the parameter value as a string.. the function never gets executed. Can you tell me what am I doing wrong here ?

1 Answer 1

0

Use a select statement for your function

SELECT [dbo].[getProdCodeById] (@id)

You can assign this to a variable before using it, as in

DECLARE @parameter varchar(15)
SET @parameter  = (SELECT [dbo].[getProdCodeById] (@id))

You can now use @parameter anywhere in your code

2
  • when I execute the function in sql server it works.. the issue however, when I specify the function call as a value to an sql parameter ( even with the select keyword ), final query considers it as just a string
    – nadunDev
    Sep 5, 2012 at 5:51
  • Firstly, assign the function to a parameter, then you can use it as your parameter Sep 5, 2012 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.