写自己需要的SQL function
2014-11-07 13:02
316 查看
在SQL中如何写一个SplitStringFunction,话不多说,上代码:
function和table都准备好,接下来测试:
结果:
里面还有个自增的[Id]字段哦,在某些情况下有可能会用上的,例如根据Id来保存排序等等。
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE function [dbo].[SplitString] ( @Input nvarchar(max), --要分割的字符串 @Separator nvarchar(max)=',', --分隔符,可以是一个字符也可以是多个字符 @RemoveEmptyEntries bit=1 ) --是否移除空字符串 returns @TABLE table --返回一个存放已经分割好的字符串的table ( [Id] int identity(1,1), [Value] nvarchar(max) ) as begin declare @Index int, @Entry nvarchar(max) set @Index = charindex(@Separator,@Input) while (@Index>0) begin set @Entry=ltrim(rtrim(substring(@Input, 1, @Index-1))) if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'') begin insert into @TABLE([Value]) Values(@Entry) end set @Input = substring(@Input, @Index+datalength(@Separator)/2, len(@Input)) set @Index = charindex(@Separator, @Input) end set @Entry=ltrim(rtrim(@Input)) if (@RemoveEmptyEntries=0) or (@RemoveEmptyEntries=1 and @Entry<>'') begin insert into @TABLE([Value]) Values(@Entry) end return end
function和table都准备好,接下来测试:
declare @str1 varchar(max), @str2 varchar(max), @str3 varchar(max) set @str1 = '1,2,3' set @str2 = '1###2###3' set @str3 = '1###2###3###' select [Value] from [dbo].[SplitString](@str1, ',', 1) select [Value] from [dbo].[SplitString](@str2, '###', 1) select [Value] from [dbo].[SplitString](@str3, '###', 0)
结果:
里面还有个自增的[Id]字段哦,在某些情况下有可能会用上的,例如根据Id来保存排序等等。
相关文章推荐
- sql中查询一张表显示多列自己需要的数据
- SQL拼接自己需要的字符串
- Linq to SQL 根据自己需要更改数据源
- 如何查看SQL Server的版本、补丁包信息?以及如何鉴别是否需要升级自己的SQL Server?
- 自己写的实现数据库事务的简单方法ExecuteSqlTran()
- ACCESS改为SQL需要注意哪几个地方!
- 为什么中国需要自己的数据库?
- [函数]function GetLocalSQLDataPath: string;
- 分解pb的数据管道语法,加入自己的SQL,灵活使用数据管道
- 移居csdn,今天想到自己的写shell的能力需要提高~
- 分解pb的数据管道语法,加入自己的SQL,灵活使用数据管道.
- 无聊的时候,写个sql,琢磨着解决自己工作中遇到的费时的问题.
- 如何快速获知需要的SPS Sql Search语法(部分转载)
- 自己需要改掉的不好习惯
- asp.net2.0:扩展ImageButton控件定制自己需要的功能
- 看了网上的大多防SQL攻击程序,自己编写了一个函数,比较完美。大家一起测测~
- 自己写的类需要重写ToString(), HashCode(), Equal()吗?
- 终于知道自己需要什么了
- sqlserver中分组查询,条件过滤,排序,写这个sql,我为自己感到骄傲
- 在水晶报表中动态的添加自己所需要的的字段