【51CTO/BBS】请教: SQL里有没有字符串组合Join的函数??

【51CTO/BBS】请教: SQL里有没有字符串组合Join的函数??

原帖地址:http://bbs.51cto.com/thread-1133863-1.html

问题描述:

VB 中有两个非常好用的字符串处理函数:

Split(字符串,分隔符)作用:将【字符串】以【分隔符】作为边界,分解成数组。 返回:一个字符串数组。

Join(字符数组,分隔符)作用:将【字符数组】中的元素,以【分隔符】作为边界,连接成一个字符串。返回:一个字符串。

请教老师们,SQL里是否有类似的函数?

解决方案:

如何用SQL Server Function实现Join


-- 使用用户定义函数,配合SELECT处理完成字符串合并处理的示例
--处理的数据
CREATE TABLE tb(col1 varchar(10),col2 int)
INSERT tb SELECT ‘a‘,1
UNION ALL SELECT ‘a‘,2
UNION ALL SELECT ‘b‘,1
UNION ALL SELECT ‘b‘,2
UNION ALL SELECT ‘b‘,3
GO
--合并处理函数
CREATE FUNCTION dbo.f_str(@col1 varchar(10))
RETURNS varchar(100)
AS
BEGIN
DECLARE @re varchar(100)
SET @re=‘‘
SELECT @[email protected]+‘,‘+CAST(col2 as varchar)
FROM tb
WHERE [email protected]
RETURN(STUFF(@re,1,1,‘‘))
END
GO
--调用函数
SELECT col1,col2=dbo.f_str(col1) FROM tb GROUP BY col1
--删除测试
DROP TABLE tb
DROP FUNCTION f_str
/*--结果
col1 col2
---------- -----------
a 1,2
b 1,2,3
--*/
GO

如何用SQL CLR实现Join


步骤一:

开始,运行Visual Studio 2012,选择“New Project”,选择“Visual C#”,“类库”,命名类库为fnConcatenate。

步骤二:

默认,Visual studio创建一个空的类命名为“Class1.cs”,右键重命名为Concatenate.cs。

步骤三:

双击“Concatenate.cs”文件,输入如下代码:

using System;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.IO;
using System.Text;
[Serializable]
[SqlUserDefinedAggregate(
Format.UserDefined, //use custom serialization to serialize the intermediate result
IsInvariantToNulls = true, //optimizer property
IsInvariantToDuplicates = false, //optimizer property
IsInvariantToOrder = false, //optimizer property
MaxByteSize = -1) //maximum size in bytes of persisted value
]
public class Concatenate : IBinarySerialize
{
/// <summary>
/// The variable that holds the intermediate result of the concatenation
/// </summary>
private StringBuilder intermediateResult;
/// <summary>
/// Initialize the internal data structures
/// </summary>
public void Init()
{
this.intermediateResult = new StringBuilder();
}
/// <summary>
/// Accumulate the next value, not if the value is null
/// </summary>
/// <param name="value"></param>
/// <param name="separator"></param>
public void Accumulate(SqlString value, SqlString separator)
{
if (value.IsNull)
{
return;
}
this.intermediateResult.Append(value.Value).Append(separator);
}
/// <summary>
/// Merge the partially computed aggregate with this aggregate.
/// </summary>
/// <param name="other"></param>
public void Merge(Concatenate other)
{
this.intermediateResult.Append(other.intermediateResult);
}
/// <summary>
/// Called at the end of aggregation, to return the results of the aggregation.
/// </summary>
/// <returns></returns>
public SqlString Terminate()
{
string output = string.Empty;
//delete the trailing comma, if any
if (this.intermediateResult != null
&& this.intermediateResult.Length > 0)
{
output = this.intermediateResult.ToString(0, this.intermediateResult.Length - 1);
}
return new SqlString(output);
}
public void Read(BinaryReader r)
{
intermediateResult = new StringBuilder(r.ReadString());
}
public void Write(BinaryWriter w)
{
w.Write(this.intermediateResult.ToString());
}
}

步骤四:

从BUILD菜单,选择“Build fnConcatenate”。编译后,在bin目录生成“fnConcatenate.dll”文件。拷贝该文件到SQL Server可访问目录,如D:\MSSQL\DATA\CLRLibraries。

步骤五:

打开SQL Server Management Studio,连接到需要部署该DLL的实例。

步骤六:

CLR集成默认在SQL Server是禁用的。执行下面的命令启用CRL集成。

sp_configure ‘show advanced options‘, 1
RECONFIGURE
GO
sp_configure ‘clr enabled‘, 1
RECONFIGURE
GO
sp_configure ‘show advanced options‘, 0
RECONFIGURE
GO

步骤七:

在应用的数据库中通过该DLL创建Assemblies。

USE AdvantureWorks2012
GO
create assembly fnConcatenate
from N‘D:\MSSQL\DATA\CLRLibraries\fnConcatenate.dll‘
with permission_set = safe
go

步骤八:

创建concatenate函数,语法类似创建标准函数,除了使用“External”定位实际的程序逻辑到你的DLL中。

create aggregate concatenate (
@value nvarchar(max),
@separator nvarchar(10)
) returns nvarchar(max)
external name fnConcatenate.Concatenate
go

步骤九:

测试concatenate函数

select dbo.concatenate(FirstName, ‘,‘) from Person.Person

时间: 2024-08-26 18:28:59

【51CTO/BBS】请教: SQL里有没有字符串组合Join的函数??的相关文章

【51CTO/BBS】请教: SQL里有没有字符串分解、组合的函数??

[51CTO/BBS]请教: SQL里有没有字符串分解.组合的函数?? 原帖地址:http://bbs.51cto.com/thread-1133863-1.html 问题描述: VB 中有两个非常好用的字符串处理函数: Split(字符串,分隔符)作用:将[字符串]以[分隔符]作为边界,分解成数组. 返回:一个字符串数组. Join(字符数组,分隔符)作用:将[字符数组]中的元素,以[分隔符]作为边界,连接成一个字符串.返回:一个字符串. 请教老师们,SQL里是否有类似的函数? 解决方案: 如

【51CTO/BBS】SQL 语句中有没有清除控制台显示(返回)数据的命令啊??

原帖地址:http://bbs.51cto.com/viewthread.php?tid=1133377&extra=&page=1 问题描述: 随着学习的进步,SQL语句变得越来越复杂. 一个SQL存储过程中,很可能调用多个存储过程.导致返回的数据凌乱不堪.   请教如何清除掉,这些不需要的返回显示的数据. 特别是用 其它编程语言调用SQL时,会导致无法获取到正确的返回数据集...... 例如:         [存储过程A]有多个SELECT语句,           SELECT @

SQL计算字符串里的子字符串出现个数

在某个页面,需要显示每条记录中有几个图片文件.图片文件名列表存储在mysql表里的photo_files字段,文件名之间用一个空格分开.类似'images\rpt201503121.jpg images\rpt201503122.jpg images\rpt201503123.jpg'这样. mysql的sql语句并不支持正则表达式函数(或者说极其有限),因此最容易想到的是用sql取出来后用PHP的explode函数放到数组里,计算数组元素个数就知道图片文件个数了.但有没有更简单的办法呢? 我的

sql里将重复行数据合并为一行,数据用逗号分隔

DECLARE @T1 table ( UserID int , UserName nvarchar(50), CityName nvarchar(50) ); insert into @T1 (UserID,UserName,CityName) values (1,'a','上海') insert into @T1 (UserID,UserName,CityName) values (2,'b','北京') insert into @T1 (UserID,UserName,CityName)

SQL Server 2008连接字符串写法大全

SQL Server 2008连接字符串写法大全 一..NET Framework Data Provider for SQL Server 类型:.NET Framework类库使用:System.Data.SqlClient.SqlConnection厂商:Microsoft 标准安全连接 Data Source = myServerAddress;Initial Catalog = myDataBase;User Id = myUsername;Password = myPassword;

51CTO下载-经典SQL语句大全.doc

一.基础 1.说明:创建数据库CREATE DATABASE database-name 2.说明:删除数据库drop database dbname3.说明:备份sql server--- 创建 备份数据的 deviceUSE masterEXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat'--- 开始 备份BACKUP DATABASE pubs TO testBack 4.说明:创建新表create

SQL里执行CLR c#代码

这里只说一个重点: 1.直接在sql里执行clr代码的时候,sql还是会报错 说没有启用 clr 执行以下代码才会起作用 EXEC sp_configure 'clr enabled', 1;  RECONFIGURE WITH OVERRIDE; 2.sql2008 只能识别.net 3.5的 参考链接: http://zhoufoxcn.blog.51cto.com/792419/859245/ https://support.microsoft.com/en-us/help/2120850

C#和Sql里【关于时间类型处理】

C#语言之“string格式的日期时间字符串转为DateTime类型”的方法 方法一:Convert.ToDateTime(string) string格式有要求,必须是yyyy-MM-dd hh:mm:ss ================================================ 方法二:Convert.ToDateTime(string, IFormatProvider) DateTime dt; DateTimeFormatInfo dtFormat = new S

在论坛中出现的比较难的sql问题:1(字符串分拆+行转列问题 SQL遍历截取字符串)

原文:在论坛中出现的比较难的sql问题:1(字符串分拆+行转列问题 SQL遍历截取字符串) 最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了. 所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路. 求SQL遍历截取字符串 http://bbs.csdn.net/topics/390648078 从数据库中读取某一张表(数据若干),然后将某一字段进行截取.比如:字段A    字段Ba/a/c      xa/b