1 set ANSI_NULLS ON
2 set QUOTED_IDENTIFIER ON
3 go
4
5
6 -- =============================================
7 -- Author: <蘭保明>
8 -- Create date: <20110316>
9 -- Description: <根據機身號和使用者發來的功能號資訊得到功能號>
10 -- =============================================
11 ALTER FUNCTION [dbo].[get]
12 (
13 @szGpsSn nvarchar(11)
14 )
15 RETURNS nvarchar(80)
16 AS
17 BEGIN
18 declare @str varchar(8000)
19 declare @str2 varchar(8000)
20 SELECT @str=[Info] FROM [south].[dbo].[DetectInfo]
21 where [Info] LIKE '%IMEI%' AND [RTKSN] =@szGpsSn
22 set @str2=right(@str,17)
23 RETURN @str2
24 END
分割函數
1 set ANSI_NULLS ON
2 set QUOTED_IDENTIFIER ON
3 go
4
5
6 ALTER function [dbo].[Get_StrArrayStrOfIndex]
7 (
8 @str varchar(1024), --要分割的字串
9 @split varchar(10), --分隔字元號
10 @index int --取第幾個元素
11 )
12 returns varchar(1024)
13 as
14 begin
15 declare @location int
16 declare @start int
17 declare @next int
18 declare @seed int
19
20 set @str=ltrim(rtrim(@str))
21 set @start=1
22 set @next=1
23 set @seed=len(@split)
24
25 set @location=charindex(@split,@str)
26 while @location<>0 and @index>@next
27 begin
28 set @start=@location+@seed
29 set @location=charindex(@split,@str,@start)
30 set @next=@next+1
31 end
32 if @location =0 select @location =len(@str)+1
33 --這兒存在兩種情況:1、字串不存在分隔字元號 2、字串中存在分隔字元號,跳出while迴圈後,@location為0,那預設為字串後邊有一個分隔字元號。
34
35 return substring(@str,@start,@location-@start)
36 end
37 --調用樣本:select dbo.Get_StrArrayStrOfIndex('8,9,4',',',2)
38 --傳回值:9
一個函數的使用
1 declare @sql nvarchar(100)
2 set @sql='A檢測故障儀器B檢測合格儀器C檢測儀器台數E倉庫入庫儀器F倉庫發貨儀器G結算回款儀器H返回退貨儀器I返回維修儀器J特殊授權儀器'
3 select substring(@sql,charindex('A',@sql),7)
4 select substring(@sql,charindex('C',@sql),7)
5 select substring(@sql,charindex('J',@sql),7)