User-Defined Functions in Sql Server SSMS

  • Thread starter WWGD
  • Start date
In summary, user-defined functions (UDFs) in SQL Server Management Studio (SSMS) allow users to encapsulate reusable code for operations such as calculations, data manipulation, and data retrieval. UDFs enhance code organization and maintainability by providing a way to create custom functions that can be invoked within SQL queries. There are two main types of UDFs: scalar functions, which return a single value, and table-valued functions, which return a table. UDFs can be created using Transact-SQL (T-SQL) and can be utilized in SELECT statements, WHERE clauses, and other SQL operations, promoting modular programming and code reuse within database applications.
  • #1
WWGD
Science Advisor
Gold Member
7,377
11,342
TL;DR Summary
Trying to figure out syntax problem with Syntax for function that takes as inputs two Real number and outputs the square root of the sum of the squares of the two numbers.
Hi, trying to write a user-defined function in SSMS Sql Server .that takes two Real numbers and outputs the square root of the
sum of their squares:

Line 152
CREATE FUNCTION dbo.Distance(@a Real, @b Real)
RETURNS Real
AS
BEGIN
SQRT(@a * @a + @b * @b)
END ;
GO

I re-checked the syntax for user-defined functions, but somehow I keep getting error messages .
Error Message:
Msg 102, Level 15, State 1, Procedure Distance, Line 5 [Batch Start Line 152]
Incorrect syntax near 'SQRT'.

any ideas?
 
Technology news on Phys.org
  • #2
are you missing the RETURN stmt:

RETURN SQRT(@a*@a + @b*@b);
 
  • Like
Likes harborsparrow and WWGD
  • #3
jedishrfu said:
are you missing the RETURN stmt:

RETURN SQRT(@a*@a + @b*@b);
Excellent, that did it. My Programmability folder runneth over. Thanks.
 
  • Like
Likes harborsparrow and jedishrfu
  • #6
Because these are reals, depending on the relative size of input values, this computation might be subject to numerical overflow. So it might be helpful to insert some error handling in there.
 
  • Like
Likes WWGD
  • #7
harborsparrow said:
Because these are reals, depending on the relative size of input values, this computation might be subject to numerical overflow. So it might be helpful to insert some error handling in there.
Thanks, any refs?
 
  • #8
MS SQL uses TRY CATCH, but what to do if an error occurs depends on so many things. I would say Google it. You might also ask an AI chatbot for help coding that.
 
  • Like
Likes WWGD

Similar threads

Replies
11
Views
2K
Replies
1
Views
2K
Replies
8
Views
1K
Replies
4
Views
6K
Replies
2
Views
3K
3
Replies
80
Views
6K
Back
Top