【发布时间】:2016-03-26 05:15:54
【问题描述】:
我正在处理一个示例查询,这是我得到的唯一outcomes 表:
**ship**
Bismarck
California
California
Duke of York
Fuso
Hood
King George V
Kirishima
Prince of Wales
Rodney
Schamhorst
South Dakota
Tennessee
Washington
West Virginia
Yamashiro
我正在用* 替换字符串中第一个和最后一个空格之间的字符。我得到了以下代码,这是正确的:
select
left(ship, charindex(' ', ship) - 1) + ' ' +
replicate('*', charindex(' ', substring(ship, charindex(' ', ship) + 1, len(ship))) + 1 -2) + ' ' +
reverse(left(reverse(ship), charindex(' ', reverse(ship)) - 1))
from outcomes
where charindex(' ', substring(ship, charindex(' ', ship) + 1, len(ship))) > 1;
代码正在运行,但我想在用户定义的函数中创建一个表变量,这样我就可以毫不费力地重用它。我用来声明表变量的代码如下,是正确的:
declare @ship_outcome table
( final_work nvarchar(30)
)
insert into @ship_outcome (final_work)
select
left(ship, charindex(' ', ship) - 1) + ' ' +
replicate('*', charindex(' ', substring(ship, charindex(' ', ship) + 1, len(ship))) + 1 -2) + ' ' +
reverse(left(reverse(ship), charindex(' ', reverse(ship)) - 1))
from outcomes
where charindex(' ', substring(ship, charindex(' ', ship) + 1, len(ship))) > 1;
select * from @ship_outcome
问题是,当我使用以下代码使其成为用户定义的函数时:
CREATE FUNCTION dbo.shippad (@tbl nvarchar(30))
RETURNS TABLE
AS
RETURN
declare @ship_outcome table
(
final_work nvarchar(30)
)
insert into @ship_outcome
select
left(ship, charindex(' ', ship) - 1) + ' ' +
replicate('*', charindex(' ', substring(ship, charindex(' ', ship) + 1, len(ship))) + 1 -2) + ' ' +
reverse(left(reverse(ship), charindex(' ', reverse(ship)) - 1))
from outcomes
where charindex(' ', substring(ship, charindex(' ', ship) + 1, len(ship))) > 1
select * from @ship_outcome
;
系统说Incorrect syntax near the keyword 'declare'.
我不知道我是怎么弄错的。请帮忙。
【问题讨论】:
标签: sql sql-server tsql user-defined-functions