开发者

SQL Sever: stored procedure that daily inserts the results of a view to custom table with a datestamp

Using the AdventureWorks Sample DB before I even work on it in on my dev server, I have created a view (Vx_CustomerAddressUpdate) and a custom table (Cx_CustomerAddressUpdate).

CREATE VIEW Vx_CustomerAddressUpdate AS 
SELECT Sales.customer.AccountNumber, 
   Sales.Customer.CustomerType, 
   Sales.Customer.ModifiedDate, 
   Sales.CustomerAddress.ModifiedDate, 
   person.Address.AddressLine1, 
   person.Address.AddressLine2, 
   person.Address.City, 
   Person.Address.PostalCode, 
   Person.StateProvince.Name, 
   Person.CountryRegion.Name
FROM Sales.Customer INNER JOIN Sales.CustomerAddress 
   ON Sales.Customer.C开发者_运维技巧ustomerID=Sales.CustomerAddress.CustomerID 
   INNER JOIN Person.Address 
   ON Sales.CustomerAddress.AddressID=Person.Address.AddressID 
   INNER JOIN Person.StateProvince 
   ON person.Address.StateProvinceID=Person.StateProvince.StateProvinceID 
   INNER JOIN Person.CountryRegion ON 
   Person.StateProvince.CountryRegionCode=Person.CountryRegion.CountryRegionCode
WHERE Person.CountryRegion.CountryRegionCode = 'US'

The stored procedure will daily insert the view rows into the custom table. The custom table has an additional field to track the date the each row was added to the custom table, which needs to be updated during the insert.

IF EXISTS (
    SELECT *
        FROM sys.procedures
    WHERE schema_id=schema_id('dbo')
    AND name = N'usp_CustomerAddressUpdate') 
DROP PROCEDURE dbo.usp_CustomerAddressUpdate
GO
CREATE PROCEDURE usp_CustomerAddressUpdate
AS
BEGIN
    SET NOCOUNT ON;
SELECT * INTO Cx_CustomerAddressUpdate 
FROM dbo.Vx_CustomerAddressUpdate
END
GO

The current challenges I'm facing are:

  1. SELECT INTO creates a new table. I need to insert into to an existing table. All of the solutions I've found for this are designed for explicit values.

  2. I've also tried SELECT INTO #temptable, but I face the same issues as above when it comes to pushing those results into the custom table.

  3. OPENROWSET seems to be overkill for an SP running on a local server


What about the typical Insert into syntax:

Insert Into Cx_CustomerAddressUpdate (<column list>,dateAdded)
Select <columns>,getdate() as dateAdded
From dbo.Vx_CustomerAddressUpdate
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜