[英]Loop in stored procedure of SQL Server
我有一个这样的存储过程:
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”(每个 select 查询的动态值),我想为“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);
但不要像这样插入:
INSERT INTO dbo.ManAlarm ([Mobile], [Content])
VALUES ('1;2;3;4;5', @msg);
Edit2 :我写了一个 function 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
关键字,因此您将 SELECT 的SELECT
放入ManAlarm
表中
但是如果你想写一个循环,你可以在CURSOR
上使用NodesMobileSMS
,但这不是一个好的性能选择。
编辑(在 Kid1412 评论之后)
如果要在NodesMobileSMS
中写入ManAlarm
中存在但具有相同值的相同行,则必须编写如下:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.