Total Pageviews

2016/02/05

[Microsoft SQL Server] Adding Rows by Using INSERT and SELECT

Problem
Assume I have a function, as user click a button it will copy last year's data and insert data into this year. How to use SQL statement to fulfill this requirement?


How To
We can use insert with a select subquery to implement this requirement
By using a SELECT subquery to specify the data values for one or more rows, such as:
INSERT INTO dbm031fa(sta_date, age, fund_id, fund_name, age_type, remark, user_id, update_date)
SELECT DATEADD(YEAR, 1, sta_date) sta_date,
       age,
       fund_id,
       fund_name,
       age_type,
       remark,
       user_id,
       CURRENT_TIMESTAMP update_date
FROM dbm031fa
WHERE year(sta_date) = year(CURRENT_TIMESTAMP)-2

Reference
[1] https://technet.microsoft.com/en-us/library/ms188263(v=sql.105).aspx

No comments: