2014-03-26 88 views
-1

我想創建一個tsql函數,它將返回一個表作爲執行tsql查詢的結果。但我總是得到錯誤。只是想知道下面的代碼有什麼問題。我創造了分裂給出postcodeidsTSQL函數頭疼

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等。並應能根據郵政編碼本身或郊區名稱進行排序。

任何幫助將不勝感激。

歡呼聲

+0

是什麼問題? –

+2

我們不知道這個功能是做什麼的。也許編輯你的「問題」,並添加一些解釋,以及一個實際的問題... –

回答

0

使用。如果你想要做的就是更改排序順序,就沒有必要訴諸動態SQL :

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 

其中,因爲你已經毫無疑問現在意識到,你不能無論如何,使用function

+0

你剛剛救了我的一天Damien..thx –

1

無法從函數執行過程或代碼。

這種失敗:

insert into @result execute (@query) 

我要補充的是,@tmp表是不是在你的代碼