我有一个这样的存储过程:
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',';');
成功!谢谢大家!
您可以编写如下:
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