如何从存储过程插入多个表

时间:2016-07-14 07:41:11

标签: sql sql-server

我有以下代码将数据插入到列中,但是没有加载到正确的列中。您认为错误是什么?

ALTER PROCEDURE [dbo].[spTESt]  
AS

DECLARE @Report TABLE (
   c1 int, c2 int, c3 int, c4 int, c5 int  
)


INSERT INTO @Report  (c1)
SELECT mass as c1 FROM other_sales
WHERE id='17501' order by mass

INSERT INTO @Report (c2)
SELECT mass as c2  FROM other_sales
WHERE id='17154' order by mass 


INSERT INTO @Report  (c3)
SELECT mass FROM other_sales
WHERE id='17156' order by mass


INSERT INTO @Report  (c4)
SELECT mass FROM other_sales
WHERE id='17500' order by mass


INSERT INTO @Report  (c5)
SELECT mass FROM other_sales
WHERE id='17501' order by mass 

它需要根据其条件进入单独的列。我应该以不同的方式构建它吗?

3 个答案:

答案 0 :(得分:2)

假设所有select语句返回单个值,您可以尝试单个语句,如下所示:

ALTER PROCEDURE [dbo].[spTESt]  
AS
--......
DECLARE @Report TABLE (c1 int, c2 int, c3 int, c4 int, c5 int )

INSERT INTO @Report  (c1, c2, c3, c4, c5) values (
(SELECT mass FROM other_sales WHERE id='17501'),
(SELECT mass FROM other_sales WHERE id='17154'),
(SELECT mass FROM other_sales WHERE id='17156'),
(SELECT mass FROM other_sales WHERE id='17500'),
(SELECT mass FROM other_sales WHERE id='17501') ) 
--....

答案 1 :(得分:1)

DECLARE 
      @Report TABLE (

c1 int ,
c2 int ,
c3 int ,
c4 int , 
c5 int

      )

DECLARE @_C1 INT
DECLARE @_C2 INT
DECLARE @_C3 INT
DECLARE @_C4 INT
DECLARE @_C5 INT

SELECT @_C1 = mass FROM other_sales
WHERE id='17501' order by mass

SELECT @_C2 = mass  FROM other_sales
WHERE id='17154' order by mass 

SELECT @_C3 = mass other_sales
WHERE id='17156' order by mass

SELECT @_C4 = mass other_sales
WHERE id='17500' order by mass

SELECT @_C5 = mass other_sales
WHERE id='17501' order by mass

INSERT INTO @Report
        ( c1, c2, c3, c4 , c5 )
VALUES  ( @_C1, -- c1 - int
          @_C2, -- c2 - int
          @_C3, -- c3 - int
          @_C4,  -- c4 - int
          @_C5  -- c5 - int
          )

答案 2 :(得分:-1)

在上一次列声明后删除逗号

DECLARE 
      @Report TABLE (

c1 int ,
c2 int ,
c3 int ,
c4 int 

      )