码迷,mamicode.com
首页 > 数据库 > 详细

SqlServer Split函数

时间:2014-09-09 18:03:09      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:blog   io   使用   ar   strong   div   cti   sp   log   

Create FUNCTION [dbo].[SplitToTable] (   
	  @SplitString nvarchar(max),     
	  @Separator nvarchar(10)=‘ ‘ 
)
 RETURNS @SplitStringsTable TABLE ( [id] int identity(1,1), [value] nvarchar(max) ) 
 AS
  BEGIN  
  	   DECLARE @CurrentIndex int;   
  	   DECLARE @NextIndex int;
  	   DECLARE @ReturnText nvarchar(max);     
  	   SELECT @CurrentIndex=1;    
  	    WHILE(@CurrentIndex<=len(@SplitString))    
  	         BEGIN           
  	         	  SELECT @NextIndex=charindex(@Separator,@SplitString,@CurrentIndex);   
  	         	            IF(@NextIndex=0 OR @NextIndex IS NULL)       
  	         	                 SELECT @NextIndex=len(@SplitString)+1;    
  	         	                 SELECT @ReturnText=substring(@SplitString,@CurrentIndex,@NextIndex-@CurrentIndex);
  	         	                 INSERT INTO @SplitStringsTable([value]) VALUES(@ReturnText); 
  	         	                 SELECT @CurrentIndex=@NextIndex+1;    
  	          END    
  	     RETURN;
   END

  使用

declare @TR NVARCHAR(50)
declare @TRS NVARCHAR(1000)
SET @TRS=‘123,456,789‘
set @TR=(select top 1 VALUE from dbo.SplitToTable(@TRS,‘,‘) order by NEWID()) --最外面一定要加括号
PRINT(@TR)

SqlServer Split函数

标签:blog   io   使用   ar   strong   div   cti   sp   log   

原文地址:http://www.cnblogs.com/gossip/p/3956275.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!