在sql中使用函数或视图

Posted

技术标签:

【中文标题】在sql中使用函数或视图【英文标题】:using of functions or views in sql 【发布时间】:2014-12-04 06:08:34 【问题描述】:

我在 SQL server 中做了函数和视图。我执行了它们,它们已成功存储。 现在我应该写什么来在另一个查询中使用这些视图或函数?!

我试过了

select something
from   FunctionName;

但系统无法识别该功能。

功能是:

create function TableOfDecades () 
returns @functiontable table
(
    decadeBegin int,
    decadeEnd       int,
    NumOfMovies int
)
as
begin
    declare @movie1 int;
    declare @movie2 int;
    declare @movie3 int;
    declare @movie4 int;
    declare @movie5 int;
    declare @year1  int;
    declare @year2  int;

    select @movie1 = count(id)
    from MOVIE
    where year >=1350 and year <1360;

    select @movie2 = count(id)
    from MOVIE
    where year >=1360 and year <1370;

    select @movie3 = count(id)
    from MOVIE
    where year >=1370 and year <1380;

    select @movie4 = count(id)
    from MOVIE
    where year >=1380 and year <1390;

    select @movie5 = count(id)
    from MOVIE
    where year >=1390 and year <1400;

    declare @maxOfMovies int;
    set @maxOfMovies = -1;

    if( @movie1 > @maxOfMovies )
    begin
        set @maxOfMovies = @movie1;
        set @year1 = 1350;
        set @year2 = 1360;
    end

    if( @movie2 > @maxOfMovies )
    begin
        set @maxOfMovies = @movie2;
        set @year1 = 1360;
        set @year2 = 1370;
    end

    if( @movie3 > @maxOfMovies )
    begin
        set @maxOfMovies = @movie3;
        set @year1 = 1370;
        set @year2 = 1380;
    end

    if( @movie4 > @maxOfMovies )
    begin
        set @maxOfMovies = @movie4;
        set @year1 = 1380;
        set @year2 = 1390;
    end

    if( @movie5 > @maxOfMovies )
    begin
        set @maxOfMovies = @movie5;
        set @year1 = 1390;
        set @year2 = 1400;
    end

    insert into @functiontable
        select @maxOfMovies, @year1, @year2;

    RETURN;
end

我执行它并将其保存在文件夹 programmability->functions->table-valued functions

【问题讨论】:

您的问题缺少很多信息。您希望如何使用这些视图?在 php、c# 等中?详细说明一下 应该是Select FunctionName(); 是sql server @a_horse_with_no_name @kya 语言是 sql @AK47 我试过但没用:( 【参考方案1】:

以下应该可以工作..

SELECT decadeBegin, decadeEnd, NumOfMovies
FROM dbo.TableOfDecades();

【讨论】:

【参考方案2】:

您的函数需要专门返回一个 Table 类型才能被另一个 sql 调用使用。 见http://technet.microsoft.com/en-us/library/ms191165%28v=sql.105%29.aspx

不同的 SQL 实现具有不同的引用表值函数的格式..

【讨论】:

以上是关于在sql中使用函数或视图的主要内容,如果未能解决你的问题,请参考以下文章

是否有列出 SQL Server 中所有内置函数的系统表或系统视图?

SQL VIEW(视图)

SQL_VIEW视图

SQL Server:将函数关联到视图的列

MySQL高级

SQL DDL 视图(VIEW)