您可以创建一个返回表的拆分函数,然后从该表中进行选择。
/***************************************************************************
**
** Function: split
** In: @ipRowData - The delimited list of items to split.
** In: @ipSplitOn - The delimiter which separates the items in @rowData.
** Returns: A table object containing the split items. The table object
** will have an ID and Data column, where ID is the number of the item
** in the original list and Data is the value of the item.
**
** Description:
** Splits a delimited set of items and returns them
** as a table object.
***************************************************************************/
CREATE FUNCTION [dbo].[split]
(
@ipRowData NVARCHAR(4000),
@ipSplitOn NVARCHAR(5)
)
RETURNS @rtnValue table
(
ID INT identity(1,1),
Data NVARCHAR(100)
)
AS
BEGIN
DECLARE
@cnt INT
Set @cnt = 1
WHILE (Charindex(@ipSplitOn,@ipRowData)>0)
BEGIN
INSERT INTO @rtnValue
( data )
SELECT Data = ltrim(rtrim(Substring(@ipRowData,1,Charindex(@ipSplitOn,@ipRowData)-1)))
SET @ipRowData = Substring(@ipRowData,Charindex(@ipSplitOn,@ipRowData)+1,len(@ipRowData))
SET @cnt = @cnt + 1
END
INSERT INTO @rtnValue (data)
SELECT DATA = ltrim(rtrim(@ipRowData))
RETURN
END
GO
样品使用情况:
select 1,data from [dbo].split('AA,AB,AC,AD', ',');
输出:
(No column name) data
1 AA
1 AB
1 AC
1 AD