我想創建一個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等。並應能根據郵政編碼本身或郊區名稱進行排序。
任何幫助將不勝感激。
歡呼聲
是什麼問題? –
我們不知道這個功能是做什麼的。也許編輯你的「問題」,並添加一些解釋,以及一個實際的問題... –