简体   繁体   中英

Write SQL Server stored procedure to insert off a select statement and loop through the values

I am a novice at SQL and I am needing to write a stored procedure to take values from a select statement and insert a particular record based on the result.

Here it goes: my current select is this:

select distinct AcctId 
from tblGlAcctDtl 
where year = '2020' 
  and Period <> 5 
  and AcctId not in (select AcctId 
                     from tblGlAcctDtl 
                     where year = '2020' 
                       and Period = 5);

This query returns a list of accounts that do not have an existing entry for any period number I insert.

For example:

AcctId
---------
11400000
12200000
12300000
12500000
12600000
13000002
13000009
13000010

What I need: for each account returned I then need to write an entry for that period. These are the values I need to insert.

Sample data that I need to insert would look like this:

AcctId   Year   Period  Actual  ActualBase  Budget  Forecast Balance
--------------------------------------------------------------------
22100000 2020     5     0.000     0.000     0.000   0.000    0.000
27500000 2020     5     0.000     0.000     0.000   0.000    0.000

Any expert help would be much appreciated.

This is what i would try:

-- Create a temp table

SELECT '2020' as year,'5' as Period, '0.000' as Actual,'0.000' as ActualBase,'0.000' as Budget,'0.000' as Forcast,'0.000' as Balance INTO #temp_table. 

--Create another temp table
select distinct AcctId 
INTO #account_ID
from tblGlAcctDtl 
where year = '2020' 
and Period <> 5 
and AcctId not in (select AcctId 
                   from tblGlAcctDtl 
                   where year = '2020' 
                   and Period = 5);
INSERT INTO Desired_table
SELECT * FROM #account_id CROSS JOIN  #temp_table

(From Question Poster) Here is the final version of what worked for me.

USE [TST] DROP TABLE TempGlAcctDtl DROP TABLE TempAccountId GO

-- Create a temp table

SELECT '2020' as Year,'5' as Period, '0.000' as Actual,'0.000' as ActualBase,'0.000' as Budget,'0.000' as Forecast,'0.000' as Balance INTO TempGlAcctDtl GO

--Create another temp table

select distinct AcctId INTO TempAccountId from tblGlAcctDtl where Year = '2020' and Period <> 5 and AcctId not in (select AcctId from tblGlAcctDtl where Year = '2020' and Period = 5); INSERT INTO tblGlAcctDtl (AcctId, Year, Period, Actual, ActualBase, Budget, Forecast, Balance) SELECT AcctId, Year, Period, Actual, ActualBase, Budget, Forecast, Balance FROM TempAccountId CROSS JOIN TempGlAcctDtl; GO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM