日期:2014-05-17 浏览次数:20538 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-17 16:03:15
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([a] varchar(4))
insert [A]
select '北京' union all
select '上海' union all
select '杭州'
--------------开始查询--------------------------
if object_id('F_Str') is not null
drop function F_Str
go
create function F_Str(@Col1 VARCHAR(200))
returns nvarchar(100)
as
begin
declare @S nvarchar(100)
select @S=isnull(@S+',','')+A from A --where A=@Col1
return @S
end
go
Select distinct a=dbo.F_Str(a) from A
go
/*
a
----------------------------------------------------------------------------------------------------
北京,上海,杭州
*/
create table #tb (col varchar(800))
insert into #tb
select '北京' union all
select '上海' union all
select '杭州'
declare @values varchar(800)
select @values = ISNULL(@values ,'')+','+COL from #tb
select STUFF (@values ,1,1,'')
drop table #tb
if object_id('[A]') is not null drop table [A]
go
create table [A]([a] varchar(4))
insert [A]
select '北京' union all
select '上海' union all
select '杭州'
--方法2. 函数,效率较高
if exists(select *&