Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.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
如何使用游标更新SQL中的多行?_Sql_Sql Server_String_Csv_Sql Update - Fatal编程技术网

如何使用游标更新SQL中的多行?

如何使用游标更新SQL中的多行?,sql,sql-server,string,csv,sql-update,Sql,Sql Server,String,Csv,Sql Update,下面是我的SQL更新,我正在尝试,但没有工作。但在使用@sampids作为INT数据类型时,它适用于单记录整数更新。任何帮助都将不胜感激。谢谢 DECLARE @sampids AS NVARCHAR(1000)='10,20,30' DECLARE @sampcursorno AS INT=0 DECLARE sample_cursor CURSOR FOR SELECT VALUE FROM Split(@sampids,',') OPEN sample_cursor FETCH N

下面是我的SQL更新,我正在尝试,但没有工作。但在使用@sampids作为INT数据类型时,它适用于单记录整数更新。任何帮助都将不胜感激。谢谢

DECLARE @sampids AS NVARCHAR(1000)='10,20,30'   
DECLARE @sampcursorno AS INT=0

DECLARE sample_cursor CURSOR FOR
SELECT VALUE FROM Split(@sampids,',')
OPEN sample_cursor
FETCH NEXT FROM sample_cursor INTO @sampcursorno

WHILE @@FETCH_STATUS = 0
    BEGIN   

        UPDATE tbl_Testing
        SET SampId = @sampcursorno

        FETCH NEXT FROM sample_cursor INTO @sampcursorno

    END

CLOSE sample_cursor

DEALLOCATE sample_cursor

我知道您想更新原始表,用输入csv列表中的每个索引替换每个
sampId

SQL Server中没有
split()
函数。您不能使用
string\u split()
,因为它不能保证返回零件的顺序

一个选项是使用递归查询拆分输入字符串,然后使用生成的数据集进行更新:

declare @sampids as nvarchar(1000)='10,20,30';

with cte as (
    select 
        1 id,
        cast(substring(@sampids, 1, charindex(',', @sampids) - 1) as int) sampid,
        substring(@sampids + ',', charindex(',', @sampids) + 1, len(@sampids)) rest
    union all
    select 
        id + 1,
        cast(substring(rest, 1, charindex(',', rest) - 1) as int),
        substring(rest, charindex(',', rest) + 1, len(rest))
    from cte
    where charindex(',', rest) > 0
)
update t
set sampid = c.id
from tbl_Testing t
inner join cte c on c.sampid = t.sampid

您使用的是哪种数据库管理系统?(该代码是特定于产品的。)“不起作用”是什么意思?从STRING_SPLIT(@sampids,,')中选择值。您的更新没有
where
子句。因此,游标的每次迭代都会更新所有行。光标完成后,所有行都将使用最后出现的值进行更新(顺便说一句,您也无法控制该值)。此外,请编辑您的问题以包含预期的输出,在注释中很难阅读