从sql中的单个select语句将数据插入两个表

时间:2017-01-21 10:38:11

标签: sql sql-server database

在我的Sql server中有一个数据库Employee,它有一个table parish。和另一个拥有表客户端和fips的客户数据库。有一个存储过程从这两个表客户端和fips中获取数据。 现在我想恢复操作。从教区表中获取数据并插入到客户端和fips中。 下面是从客户端和fips获取数据的存储过程。

ALTER PROCEDURE [dbo].[Rpt_getexportparish] @clientID              AS INT,
                                            @assessment_type       AS NVARCHAR(10),
                                            @political_subDivision AS NVARCHAR(10),
                                            @district              AS NVARCHAR(10),
                                            @acct_status           AS NVARCHAR(10),
                                            @millage_type          AS NVARCHAR(10),
                                            @tax_year              AS NVARCHAR(10)
AS
  BEGIN
      SELECT FIPScode             AS fips_code,
             f.cnty_name          AS gov_name,
             c.NAME               AS gov_agency,
             PhysicalAddress1     AS address2,
             PhysicalAddress2     AS address1,
             TaxYear              AS tax_year,
             PhysicalAddressCity  AS city,
             PhysicalAddressState AS state,
             PhysicalAddressZip   AS zip,
             AssessorName         AS assr_name
      FROM   Clients c
             JOIN fips f
               ON c.FIPScode = f.cnty_fips
      WHERE  id = @clientID
             AND place_fips = @political_subDivision
  END 

我想要反过来。从教区中选择数据并插入到客户端和fips表中。那是什么是sql查询。

表客户端和fips都没有关系。

1 个答案:

答案 0 :(得分:0)

OUTPUT命令允许您使用单个查询插入辅助表。

这是一个如何运作的例子

DROP TABLE #SOURCE
DROP TABLE #TARGET1
DROP TABLE #TARGET2

CREATE TABLE #SOURCE(ID INT IDENTITY(1,1),Val FLOAT)
GO
CREATE TABLE #TARGET1(ID INT,Val FLOAT)
GO
CREATE TABLE #TARGET2(ID INT,Val FLOAT)
GO
--ADD 10 ROWS TO SOURCE TABLE
INSERT INTO #SOURCE VALUES (RAND())
GO 10

INSERT INTO #TARGET1
OUTPUT INSERTED.* INTO #TARGET2
SELECT
    *
FROM
    #SOURCE