创建表并插入值:
CREATE TABLE [dbo].[test3](
[id] [int] NULL,
[value] [varchar](20) NULL
)
insert into [dbo].[test3] values (1,'P126');
解决方案 1:
我们可以通过选择查询将表中的值传递给变量@t。
DECLARE @t nvarchar(10);
select @t=value from [dbo].[test3];
WITH cte AS (
SELECT 1 id, LEFT(@t, 1) col, RIGHT(@t, LEN(@t)-1) txt
UNION ALL
SELECT id+1, LEFT(txt, 1), RIGHT(txt, LEN(txt)-1)
FROM cte
WHERE LEN(txt) >= 1
)
SELECT id, col
FROM cte
解决方案 2:
我们可以定义一个函数。
创建一个函数来分割字符串:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create function [dbo].[MySplitStringFunc]( @str nvarchar(100))
returns @tableName Table
(
id int identity(1,1),
value nchar(1)
)
as
begin
declare @insertStr nvarchar(100)
declare @newstr nvarchar(100)
declare @id int
set @id=1;
set @insertStr = substring(@str,@id,1)
set @newstr = stuff(@str,@id,1,'')
begin
insert @tableName Values(@insertStr)
end
while(len(@newstr)>1)
begin
set @id =@id + 1
set @insertStr = substring(@str,@id,1)
insert @tableName values(@insertStr)
set @newstr = stuff(@newstr,1,1,'')
end
insert @tableName values(@newstr)
return
end
调用函数并返回一个表:
declare @string nvarchar(100)
select @string=value from [dbo].[test3]
select * from [dbo].[MySplitStringFunc](@string)