4

I've created a user defined scalar function in sql server 2005, and I want it to return me the id based on the passing parameter name. But the following function always returns me null, even the passing name already exists in table. Could anyone please tell me the reason?

create function IsNameExist(@Name varchar)
returns int
As
Begin
Declare @Id int
Select @Id = ProductId from [Product] where ProductName = @Name
return @Id
End
5
  • can you give an example of the statement were you're using this UDF? Commented Jul 25, 2011 at 11:18
  • select dbo.isNameExist('wheat'); Commented Jul 25, 2011 at 11:23
  • 2
    Note that @Name will truncate @ 30 chars as your varchar is not declared with a maximum size Commented Jul 25, 2011 at 11:24
  • I can see no syntactic failure Commented Jul 25, 2011 at 11:25
  • 1
    Try with create function IsNameExist(@Name varchar(200)) as Alex's suggestion. Commented Jul 25, 2011 at 11:28

1 Answer 1

9

Please note that you did not specify the length for the function parameter datatype. So by default in this case it becomes 1 and your query inside the function fails. Try this and see

create function 
IsNameExist(@Name varchar(100)) 
returns int As 
Begin 
Declare @Id int 
Select @Id = ProductId from [Product] where ProductName = @Name 
return @Id 
End 

Also refer this post http://beyondrelational.com/blogs/madhivanan/archive/2007/12/04/column-length-and-data-length.aspx

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.