TSQL功能令人头疼

时间:2014-03-26 07:17:07

标签: sql-server tsql

我正在尝试创建一个tsql函数,它会在执行tsql查询时返回一个表。但我总是得到错误。只是想知道下面我的代码有什么问题。

ALTER FUNCTION [dbo].[fnGetPostcodeBrowseByIds]
(
    @PostCodes varchar(1000),
    @SortBy int
)
RETURNS @result TABLE 
(
        postcode int,
        suburb varchar(100),
        [state] varchar(3)
)
AS
BEGIN
    declare @tmp table
    (
        postcode int,
        suburb varchar(100),
        [state] varchar(3)
    )
    declare @query varchar(1000)
    if @SortBy = 0
       begin
            set @query = N' select a.postcodeid as postcode,b.name as 
            suburb,a.state from postcode a inner join suburb b on
            a.postcodeid = b.postcodeid where a.postcodeid 
            in (select data from 
            dbo.fnSplit(''' + @PostCodes + ''','','')) order by a.postcodeid asc'
       end
    else
       begin
            set @query = N' select a.postcodeid as postcode,b.name as
            suburb,a.state from postcode a inner join suburb b on 
            a.postcodeid = b.postcodeid where a.postcodeid 
            in (select data from 
            dbo.fnSplit(''' + @PostCodes + ''','','')) order by b.Name asc'
       end
       insert into @result execute (@query)
    return
END

和我创建的用于拆分给定邮政编码的其他功能是

ALTER FUNCTION [dbo].[fnSplit]
(
    @String NVARCHAR(4000),
    @Delimiter NCHAR(1)
)
RETURNS TABLE 
AS
RETURN 
(
    WITH Split(stpos,endpos) 
    AS(
        SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
        UNION ALL
        SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
            FROM Split
            WHERE endpos > 0
    )
    SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
        'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
    FROM Split
)

fnSplit找不到但第一个函数没有。

此函数用于根据给定的邮政编码返回邮政编码,子郊名和状态列表,后者是一个分隔的字符串。示例:2001,2200,3400等。并且应该能够根据邮政编码id本身或郊区名称进行排序。

任何帮助都会受到赞赏。

欢呼声

2 个答案:

答案 0 :(得分:1)

无法从函数执行过程或代码。

这失败了:

insert into @result execute (@query)

我应该补充说,代码中没有使用@tmp表

答案 1 :(得分:0)

如果您只想更改排序顺序,则无需使用动态SQL 1

ALTER FUNCTION [dbo].[fnGetPostcodeBrowseByIds]
(
    @PostCodes varchar(1000),
    @SortBy int
)
RETURNS @result TABLE 
(
        postcode int,
        suburb varchar(100),
        [state] varchar(3)
)
AS
BEGIN
    insert into @result (postcode,suburb,state)
    select a.postcodeid as postcode,b.name as suburb,a.state
    from postcode a
           inner join
         suburb b on a.postcodeid = b.postcodeid
    where a.postcodeid in (select data from dbo.fnSplit(@PostCodes,','))
    order by
        CASE WHEN @Sort = 0 THEN a.postcodeid END asc,
        CASE WHEN @Sort <> 0 THEN b.Name END asc

END

1 正如您现在已经意识到的那样,无论如何都不能在function内使用。