Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server insert multiple records with same datetime

Tags:

sql

sql-server

I have a table that has a datetime column that I wish to insert multiple records into at the same time. It is necessary that the datetime is exactly the same so I can late compare which records were inserted together. Is it sufficient to do something like this:

INSERT INTO Table(Date, ID, etc...)
VALUES (GETDATE(), ...)

Or should I declare a variable earlier in the stored procedure to hold the current time and just use that as the value to insert.

I have tested and it seems like the first method works fine, I just want to be 100% certain.


Edit: I think the question is better stated as "How often does GETDATE() get executed in a stored procedure?"

like image 321
goalie7960 Avatar asked Apr 19 '26 04:04

goalie7960


2 Answers

GETDATE() is evaluated once per query. There's no need to declare a variable.

like image 110
Joe Stefanelli Avatar answered Apr 22 '26 00:04

Joe Stefanelli


Yes, declare a variable to hold the current time if you want to use that approach. You could also create a parent record and assign a single datetime to it, and then write the parent ID into the child records. Relying on a DateTime stamp will probably work OK, but it seems a little dirty.

like image 37
James Hill Avatar answered Apr 22 '26 01:04

James Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!