SQL Server存储过程中的循环

问题描述 投票:0回答:1

我有一个这样的存储过程:

ALTER PROCEDURE [dbo].[insert_sms] 
    (@msg VARCHAR(MAX), @nodeid INT)    
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO dbo.ManAlarm ([Mobile], [Content]) 
    VALUES ((SELECT Mobile FROM NodesMobileSMS WHERE NodeID = @nodeid), @msg);
END

我如何编写循环脚本,使(select Mobile from NodesMobileSMS)中的每个手机号码都能执行插入查询?

编辑

select Mobile 
from NodesMobileSMS 
where NodeID = @nodeid

将返回“ 1; 2; 3; 4; 5”(每个选择查询的动态值),我想为“ 1; 2; 3; 4; 5”中的每个数字编写一个循环,它将插入ManAlarm中的一行:

INSERT INTO dbo.ManAlarm ([Mobile], [Content]) 
VALUES (1, @msg);
INSERT INTO dbo.ManAlarm ([Mobile], [Content]) 
VALUES (2, @msg);
...
INSERT INTO dbo.ManAlarm ([Mobile], [Content]) 
VALUES (5, @msg);

但是NOT像这样插入:

INSERT INTO dbo.ManAlarm ([Mobile], [Content]) 
VALUES ('1;2;3;4;5', @msg);

Edit2:我写了一个函数splitString并插入查询:

INSERT INTO dbo.ManAlarm ([Mobile], [Content]) 
SELECT *,'message' from dbo.splitString('1;2;3;4;5',';');

成功!谢谢大家!

sql-server stored-procedures sql-server-2008-r2
1个回答
1
投票

您可以编写如下:

INSERT INTO dbo.ManAlarm([Mobile], [Content]) 
SELECT Mobile, @msg from NodesMobileSMS where NodeID = @nodeid

在上面的查询中,我只是删除了VALUES关键字,因此您将ManAlarm的输出放在了SELECT表中>

但是,如果要编写循环,可以在CURSOR上使用NodesMobileSMS,但在性能上不是一个好的选择。

编辑(在Kid1412评论之后)]] >>

如果要在ManAlarm中进行写入,则在NodesMobileSMS中存在相同的行,但必须具有相同的值,如下所示:

INSERT INTO dbo.ManAlarm([Mobile], [Content]) 
SELECT 1, @msg from NodesMobileSMS where NodeID = @nodeid

如果要添加任意数量的行,您可以将INSERT放入FOR循环中

编辑(在Kid1412说他使用Sql Server 2016之后)]

INSERT INTO dbo.ManAlarm([Mobile], [Content]) 
SELECT STRING_SPLIT(Mobile, ';'), @msg from NodesMobileSMS where NodeID = @nodeid
© www.soinside.com 2019 - 2024. All rights reserved.