【发布时间】:2017-03-30 00:12:37
【问题描述】:
我正在研究SQL Server(2005、2008 和 2012)
我想通过使用 UDF 从 varchar 列中提取前五个数字
输入:
rrr123ddd4567ddd19828www2
123hhhsss124ss18762s
qq12349wsss12376ss
输出:
19828
18762
12349
我的足迹如下:
DECLARE
@myString VARCHAR(1000),
@temp VARCHAR(100),
@position INT,
@ExecuteInsert nvarchar (500),
@FirstChar bit
SET @myString = 'rrr123ddd4567ddd19828www2'
SET @position = 1
SET @FirstChar = 1
WHILE @position <= LEN(@myString)
BEGIN
IF (ISNUMERIC(SUBSTRING(@myString,@position,1))) = 1
BEGIN
SET @temp = isnull(@temp,'') + SUBSTRING(@myString,@position,1)
SET @FirstChar = 1
END
ELSE /* The char is alphabetical */
BEGIN
if (@FirstChar= 1)
BEGIN
SET @temp = isnull(@temp,'') + ','
SET @FirstChar = 0
END
END
SET @position = @position + 1
END
IF (RIGHT(@temp,1) <> ',')
BEGIN
SET @temp = @temp + ','
END
SELECT @temp = REPLACE(','+ @temp + ',',',,','')
SELECT @temp = Replace (@temp,',','''),(''')
Select @temp = '(''' + @temp + ''')'
Create table #temp
(
col1 varchar(100)
)
SET @ExecuteInsert = 'insert into #temp values ' + @temp
Execute sp_executesql @ExecuteInsert
select top 1 col1 from #temp
where LEN(col1) = 5
drop table #temp
-- Output >> 19828
前面的查询与字符串输入配合得很好,但我想在UDF 中使用此代码以将其与列一起使用。
如果我在 UDF 中使用上一个查询,则会引发以下错误:
无法从函数内访问临时表。
编辑
如果我使用 Table variable ,我会得到下一个错误:
只能执行函数和一些扩展存储过程 从函数内部。
任何帮助将不胜感激。
【问题讨论】:
-
更改代码以使用表变量而不是临时表。
-
@R.Richards 将其更改为表变量后出现此错误找不到列“dbo”或用户定义的函数或聚合“dbo.GetFirstFiveNumbers”,或者名称不明确。
标签: sql-server replace substring user-defined-functions