Syntax of Scalar valued function
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date, ,>
-- Description: <Description, ,>
-- =============================================
CREATE FUNCTION <Scalar_Function_Name, sysname, FunctionName>
(
-- Add the parameters for the function here
<@Param1, sysname, @p1> <Data_Type_For_Param1, , int>
)
RETURNS <Function_Data_Type, ,int>
AS
BEGIN
-- Declare the return variable here
DECLARE <@ResultVar, sysname, @Result> <Function_Data_Type, ,int>
-- Add the T-SQL statements to compute the return value here
SELECT <@ResultVar, sysname, @Result> = <@Param1, sysname, @p1>
-- Return the result of the function
RETURN <@ResultVar, sysname, @Result>
END
GO
Example :
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Sandeep Mhatre
-- Create date: 1 feb 2012
-- Description: Function to check wheater the no is whole no or double
-- =============================================
CREATE FUNCTION udfCheckNo
(
@Number numeric (18,2)
)
RETURNS varchar(50)
AS
BEGIN
Declare @TextNo Varchar(50)
--Declare @TextNo Varchar(50)
Declare @Numeric varchar (20)
Declare @Double varchar (20)
Select @Numeric = Convert(varchar , round(15.25 , 2) )
Select @Double = cast ( round(15.25 , 0) as decimal(10,2) )
if(@Numeric = @Double)
Begin
set @TextNo = cast( @Numeric as decimal(20,0))
--Print @Numeric
--print @Double
End
else
Begin
---print @Numeric
set @TextNo = cast( @Numeric as decimal(20,2))
End
--print 'textno ' + @TextNo
RETURN @TextNo
END
GO
Using the Function
select col1, col2 , dbo.udfCheckNo(col3) from
table1
where condition1
Comments
Post a Comment