插入到select语句sql server

时间:2015-03-10 14:16:12

标签: sql

我创建了一个从另一个表插入数据的过程,如下所示:

DROP PROCEDURE IF EXISTS STP_addCompanySection;
DELIMITER //
CREATE PROCEDURE STP_addCompanySection ()
BEGIN

insert into companySection(categoryName,description) 
select categoryName,description from BusinessCat where deleted='0';

END \g
DELIMITER ;

我可以在插件上添加另一列,如下所示:

DROP PROCEDURE IF EXISTS STP_addCompanySection;


DELIMITER //
CREATE PROCEDURE STP_addCompanySection (
IN inCompanyId int
)
BEGIN

insert into companySection(categoryName,description,comId) 
(select categoryName,description from BusinessCat where deleted='0' ,inCompanyId);
select LAST_INSERT_ID() id;

END \g
DELIMITER ;

感谢

4 个答案:

答案 0 :(得分:1)

尝试类似:

insert into companySection(categoryName,description,comId) 
(select categoryName,description, inCompanyId 
 from BusinessCat 
 where deleted='0');

答案 1 :(得分:0)

你可以这样做:

insert into companySection(categoryName,description,comId) 
select categoryName,description,inCompanyId from BusinessCat where deleted='0';
select LAST_INSERT_ID() id;

答案 2 :(得分:0)

其他用户错过了这个问题。动态SQL可能是您的解决方案。您的输入参数值将是您要注入的任何列的字符串。您的存储过程将包含:

DECLARE @MySQL VARCHAR(MAX);

@MySQL = 'insert into companySection(categoryName,description,comId)
(select categoryName,description ' + ,inCompanyId + ' from BusinessCat where     deleted='0' );' 

EXEC (@MySQL);

请注意,如果您不了解这一点,则非常容易受到SQL注入攻击并阅读该主题。

答案 3 :(得分:-1)

当然,将其添加到选择列表中:

insert into companySection(categoryName,description,comId) 
(select categoryName,description, inCompanyID from BusinessCat where deleted='0');