Is there anyway of having the default value in a table be the value from the row above ?
Microsoft SQL Server 2008Microsoft SQL ServerMicrosoft SQL Server 2005
Last Comment
dkilby
8/22/2022 - Mon
Éric Moreau
from SSMS? no.
Member_2_861731
What's your definition of "row above"? This is pretty vague, as the row above can change easily (think an order by clause).
Éric Moreau
from what I understand from the question, is that the person want to have SSMS automatically set default values when entering data using SSMS "edit top 200 rows". but I can be totally wrong here!
I thought OP meant get "value" of last inserted row, and make that the default for the new row.
We'll see if there's any clarification
Nakul Vachhrajani
Do you mean as part of a default constraint?
No.
Reason: In any RDBMS, order of the records is not important - a table is really just a set of data of the same type. To us, they are rows "above" and "below" because we "see" a list. Actually it is just a set of records.
Therefore, allowing to use the records from other rows violates basic RDBMS principles.
Workaround: Use a scalar valued function if it is utmost necessary to do this. Beware that you will run into concurrency, locking and other such issues.
My recommendation: Avoid the workaround.
dkilby
ASKER
i am taking data from an excel sheet and putting into a temp table, i then need to move the data to actual table, the problem in the spreadsheet the CustomerID is for the one row and then blank until the orders for that customer ends and then a new CustomerID / Orders starts.
So i was thinking of a default value, but another thought would be to do something like an update statement before moving the data that updates the NULL value with the value above - or is that not possible either ?
how do you take the data from Excel to insert into your SQL table? you have an application or a SSIS package or ??? This is the place to preserve the last customer ID to repeat the value if empty.
dkilby
ASKER
unfortunately it is a automated process and I dont have access to change the source, that is why i was hoping i could do it on the database side
Éric Moreau
purely table side, there is nothing you can do. You could build a Stored Proc that would retrieve the data and copy the value from the previous row if the current is empty but even there, you would need to change your process to connect to the return of the stored proc which apparently you can't.
why not try to add something to your excel file then? a bit a vba code that would fill empty cells? but the user would have to activate somehow.
No the normal database DEFAULT syntax will not do what you want but there are other ways to work it. Are you writing the insert statement that is loading it from the temp table into the actual one? And what version of SQL Server are you on as that determines how it need to be done.
dkilby
ASKER
i am using SQL 2014 and yes using a sql statement to move the data from temp table to real table,