SQL自定义函数
合集下载
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
调用
select * from f2(1,1)
调用自定义函数
-- 注意,前缀dbo好像不能省略,不清楚原因 select dbo.round2(123.456,2)
删除自定义函数
drop function round2
2, 自 定 义 函 数 --返 回 一 个 表 结 构
2.1 返回的表结构自己定义
CREATE FUNCTION f1 (
-- Add the parameters for the function here @p1 int, @p2 char ) RETURNS @Table_Var TABLE ( -- Add the column definitions for the TABLE variable here c1 int, c2 int ) AS BEGIN -- Fill the table variable with the rows for your result set insert into @Table_Var values(1,2) insert into @Table_Var values(1,2) RETURN END GO
if @p1 > @interval set @Result = round(cast(@p1 as float) - cast( @interval as float),@scale)
else set @Result = 0
-- Return the result of the function RETURN @Result END
调用
select * from f1(1,1)
2.2 返回的表结构不明确定义,由 select语句决定
CREATE FUNCTION f2 (
-- Add the parameters for the function here @p1 int, @p2 char ) RETURNS TABLE AS RETURN ( -- Add the SELECT statement with parameter references here SELECT top 10 * from dbo.DQuestionData ) GO
SQL自 定 义 函 数
1, 自 定 义 函 数 --返 回 单 一 值
CREATE FUNCTION [dbo].[Round2] (
-- Add the parameters for the function here @p1 sql_variant, -- decimal numbers @scale int ) RETURNS sql_variant AS BEGIN -- Declare the return variable here DECLARE @Result sql_variant,@interval sql_variant
-- Add the T-SQL statements to compute the return value here if @scale >=0
set @interval = 1.0/POWER(10,@scale) * 0.5 else
set @interval = POWER(10,@scale) * 0.5
select * from f2(1,1)
调用自定义函数
-- 注意,前缀dbo好像不能省略,不清楚原因 select dbo.round2(123.456,2)
删除自定义函数
drop function round2
2, 自 定 义 函 数 --返 回 一 个 表 结 构
2.1 返回的表结构自己定义
CREATE FUNCTION f1 (
-- Add the parameters for the function here @p1 int, @p2 char ) RETURNS @Table_Var TABLE ( -- Add the column definitions for the TABLE variable here c1 int, c2 int ) AS BEGIN -- Fill the table variable with the rows for your result set insert into @Table_Var values(1,2) insert into @Table_Var values(1,2) RETURN END GO
if @p1 > @interval set @Result = round(cast(@p1 as float) - cast( @interval as float),@scale)
else set @Result = 0
-- Return the result of the function RETURN @Result END
调用
select * from f1(1,1)
2.2 返回的表结构不明确定义,由 select语句决定
CREATE FUNCTION f2 (
-- Add the parameters for the function here @p1 int, @p2 char ) RETURNS TABLE AS RETURN ( -- Add the SELECT statement with parameter references here SELECT top 10 * from dbo.DQuestionData ) GO
SQL自 定 义 函 数
1, 自 定 义 函 数 --返 回 单 一 值
CREATE FUNCTION [dbo].[Round2] (
-- Add the parameters for the function here @p1 sql_variant, -- decimal numbers @scale int ) RETURNS sql_variant AS BEGIN -- Declare the return variable here DECLARE @Result sql_variant,@interval sql_variant
-- Add the T-SQL statements to compute the return value here if @scale >=0
set @interval = 1.0/POWER(10,@scale) * 0.5 else
set @interval = POWER(10,@scale) * 0.5