我的工作SQL Server
(2005,2008 & 2012)返回內UDF
我想通過使用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前面的查詢,下面的錯誤認識:
Cannot access temporary tables from within a function.
編輯
如果我用表變量,我得到了一個錯誤:
Only functions and some extended stored procedures can be executed from within a function.
任何幫助將不勝感激。
更改代碼以使用表變量,而不是一個臨時表。 –
@ R.Richards將其更改爲表變量後,我得到此錯誤找不到列「dbo」或用戶定義函數或聚合「dbo.GetFirstFiveNumbers」,或名稱不明確。 –