Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用存储过程在SQLServer2008中从字符串添加值?_Sql_Sql Server_Sql Server 2008_Stored Procedures - Fatal编程技术网

如何使用存储过程在SQLServer2008中从字符串添加值?

如何使用存储过程在SQLServer2008中从字符串添加值?,sql,sql-server,sql-server-2008,stored-procedures,Sql,Sql Server,Sql Server 2008,Stored Procedures,如何从字符串中插入值,如1,2,3,4;7,3,8,4;3,9,0,4; 在SQL Server 2008中使用存储过程,其中;是否表示新行的开头,是否表示新列?e、 g值1 2 3 4将插入到相应的列中,并在“;”之后插入下一个值,即7 3 8 4,将被插入到相同的第7列,然后插入到第一列,依此类推 我找到了一些答案,但它们比以往任何时候都更让我困惑 编辑: 我找到的大多数答案都是通过使用LTRIM和RTRIM在两列中插入值,但我在不同的表中有不同的列数。 我希望这能解释我的问题我为您准备了一

如何从字符串中插入值,如1,2,3,4;7,3,8,4;3,9,0,4; 在SQL Server 2008中使用存储过程,其中;是否表示新行的开头,是否表示新列?e、 g值1 2 3 4将插入到相应的列中,并在“;”之后插入下一个值,即7 3 8 4,将被插入到相同的第7列,然后插入到第一列,依此类推

我找到了一些答案,但它们比以往任何时候都更让我困惑

编辑:

我找到的大多数答案都是通过使用LTRIM和RTRIM在两列中插入值,但我在不同的表中有不同的列数。
我希望这能解释我的问题

我为您准备了一个SQL脚本,它将输入字符串拆分两次,然后将其转换为行数据,最后插入到数据库表中

为了分割字符串数据,我使用了 首先,您需要在数据库上创建此函数

不幸的是,如果您不使用SQL Server 2016,我们必须创建拆分函数

我曾经在一条语句中管理所有这些步骤,而不是使用SQL子选择语句或临时表

要了解多个CTE结构,请参阅上述教程

我希望有帮助 请先检查测试数据库上的以下脚本

declare @str varchar(max) = '1,2,3,4;7,3,8,4;3,9,0,4;'

create table stringtorows (id int, col1 int, col2 int, col3 int, col4 int)

;with cte as (
select
    id rowid, val rowdata
from dbo.split(@str,';')
where val <> ''
), cte2 as (
select
    rowid, id colid, val coldata
from cte
cross apply dbo.Split(rowdata,',')
), cte3 as (
select
    rowid,
    case when colid = 1 then coldata end col1,
    case when colid = 2 then coldata end col2,
    case when colid = 3 then coldata end col3,
    case when colid = 4 then coldata end col4
from cte2
)
insert into stringtorows
select
    rowid, max(col1) col1, max(col2) col2, max(col3) col3, max(col4) col4
from cte3
group by rowid

select * from stringtorows

你说添加它们是什么意思?你发现什么样的答案让你困惑?什么让你困惑?非常感谢,先生。我不能告诉你你帮了我多少!!!