0

I have tbl_emp like that:

empid
1  
2
3
4

And tbl_att like that:

empid     workingdate
1         2017-05-11
2         2017-05-13
3         2017-05-14
...........
...........

I have a job in SQL Server agent to execute step every Sunday and I want that job to insert a row for each empid with that day into tbl_att. Let's say Sunday is 2017-05-22 so I want it like that:

empid     workingdate
1         2017-05-22
2         2017-05-22
3         2017-05-22

It means that I want it to insert into tbl_att for all empid with the same day (task execution day), so can anyone guide me a query that I need to put into my step command?

5
  • 3
    Sounds like a simple update statement Commented May 25, 2017 at 4:11
  • The row is not yet exist, how can we use update statement? Commented May 25, 2017 at 4:16
  • If it doesnt exist... why are the dates different? Commented May 25, 2017 at 4:17
  • it's a previous data, and what i want is to insert new row to table for every Sunday, not update the existed record to Sunday bro/sis. Commented May 25, 2017 at 4:19
  • What insert statement you tried? Did it insert the record? What error did you see? Commented May 25, 2017 at 4:43

3 Answers 3

2

Try this,

INSERT INTO tbl_att SELECT empid,CAST(GETDATE() AS DATE) FROM tbl_emp;
Sign up to request clarification or add additional context in comments.

Comments

0
insert into tbl_att (empid, workingdate)
Select empid,cast(getdate() as date) from tbl_emp

As you run the job on every Sunday, above query will insert the data as per your expectation I believe. FYI, But it depends on the system date

4 Comments

But can you explain me about this line of query?
Getdate will fetch the current system date. As you're running on sunday, it will fetch the Sundays equivalent system date.
Thanks you for your explanation
How would you eliminate the duplicate records not to be inserted
0

Hope it helps you

CREATE TABLE #tbl_att (empid INT,workingdate DATE)

CREATE TABLE #EmpidTab (empid INT)

INSERT INTO #EmpidTab
SELECT 1 UNION ALL 
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4
SELECT * FROM #EmpidTab

INSERT INTO #EmpidTab
SELECT 5

INSERT INTO #tbl_att
SELECT Empid
    ,Getdate() AS workingdate
FROM #EmpidTab i
WHERE NOT EXISTS (
        SELECT 1
        FROM #tbl_att t
        WHERE t.empid = i.Empid
        ) --Eliminate duplicte insertion of empid's 

SELECT @@ROWCOUNT AS NoRowsInserted

SELECT *
FROM #tbl_att

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.