Link to home
Start Free TrialLog in
Avatar of Lev Seltzer
Lev SeltzerFlag for Israel

asked on

Adding function in SQL Server Management Studio

I asked a question some time ago (https://www.experts-exchange.com/questions/21878497/Combine-child-records-into-flat-table.html) regarding a function in an MSSQL database. The function got lost during a database transfer, and I need to recreate it. I am now using MS SQL Server Management Studio 10, and I am confused by all the choices for functions. Based on the original question (see link), where should I enter this function into the database?

Thank you.
ASKER CERTIFIED SOLUTION
Avatar of Rajkumar Gs
Rajkumar Gs
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Now if there is no error message on bottom message window, it's created.

To test your function with the SELECT query copy & paste the select query from that link in another 'Query Window' and press F5

Raj
Avatar of Lev Seltzer

ASKER

This worked almost perfectly. I am getting an error in the code when I execute it.
The actual function and the select statement appears in the attached snippet. When I execute the select statement, I get this error:
Msg 536, Level 16, State 5, Line 1
Invalid length parameter passed to the SUBSTRING function.

Any suggestions?

SELECT Book.*, dbo.udf_AuthorList(Book.BookID) AS Authors FROM Book

CREATE FUNCTION dbo.udf_AuthorList (@ProductID int)
RETURNS varchar(500)
BEGIN
DECLARE @List varchar(500)
SET @List = ''

SELECT @List = @List + FirstName + ' ' + Lastname + ', '
FROM isrbksh_admin.qprAuthors
WHERE ProductID = @ProductID
ORDER BY LastName

SET @List = SUBSTRING(@List, 1, LEN(@List) - 1)
RETURN @List
END

Open in new window

When you execute this SELECT statement, chance that error may occur depending on the value of @List variable in that function.

Can you spot, which record is causing this error in that select statement. ?
SELECT Book.*, dbo.udf_AuthorList(Book.BookID) AS Authors FROM Book

Post the result of this query.

Raj
SELECT TOP 5 FirstName, Lastname
FROM isrbksh_admin.qprAuthors 
ORDER BY LEN(FirstName + ' ' +  Lastname)

Open in new window

Using your latest code, I was able to determine that some child records were missing, and that caused the data error. I added the child records, and everything works properly now. Thank you for your help in getting this to work.