Solved

MS SQL + Default Value + Row Above

Posted on 2016-08-02
13
52 Views
Last Modified: 2016-08-02
Is there anyway of having the default value in a table be the value from the row above ?
0
Comment
Question by:dkilby
  • 4
  • 4
  • 2
  • +3
13 Comments
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
from SSMS? no.
0
 
LVL 13

Expert Comment

by:LIONKING
Comment Utility
What's your definition of "row above"? This is pretty vague, as the row above can change easily (think an order by clause).
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
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!
0
 
LVL 13

Expert Comment

by:LIONKING
Comment Utility
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
0
 
LVL 11

Expert Comment

by:Nakul Vachhrajani
Comment Utility
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.
0
 

Author Comment

by:dkilby
Comment Utility
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 ?
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
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.
1
 

Author Comment

by:dkilby
Comment Utility
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
0
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
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.
0
 
LVL 26

Expert Comment

by:Chris Luttrell
Comment Utility
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.
0
 

Author Comment

by:dkilby
Comment Utility
i am using SQL 2014 and yes using a sql statement to move the data from temp table to real table,
0
 
LVL 6

Accepted Solution

by:
Manju earned 500 total points
Comment Utility
An example query and you can modify as per your tables

/* Test Data & Table */
DECLARE @Customers TABLE
    (Dates datetime,
     Customer integer,
     Value integer)

    INSERT  INTO @Customers
    VALUES  ('20100101', 1, 12),
        ('20100101', 2, NULL),
        ('20100101', 3, 32),
        ('20100101', 4, 42),
        ('20100101', 5, 15),
        ('20100102', 1, NULL),
        ('20100102', 2, NULL),
        ('20100102', 3, 39),
        ('20100102', 4, NULL),
        ('20100102', 5, 16),
        ('20100103', 1, 13),
        ('20100103', 2, 24),
        ('20100103', 3, NULL),
        ('20100103', 4, NULL),
        ('20100103', 5, 21),
        ('20100104', 1, 14),
        ('20100104', 2, NULL),
        ('20100104', 3, NULL),
        ('20100104', 4, 65),
        ('20100104', 5, 23) ;

/* CustCTE - This gives us a RowNum to allow us to build the recursive CTE CleanCust */
WITH    CustCTE
          AS (SELECT    Customer,
                        Value,
                        Dates,
                        ROW_NUMBER() OVER (PARTITION BY Customer ORDER BY Dates) RowNum
              FROM      @Customers),

/* CleanCust - A recursive CTE. This runs down the list of values for each customer, checking the Value column, if it is null it gets the previous non NULL value.*/
        CleanCust
          AS (SELECT    Customer,
                        ISNULL(Value, 0) Value, /* Ensure we start with no NULL values for each customer */
                        Dates,
                        RowNum
              FROM      CustCte cur
              WHERE     RowNum = 1
              UNION ALL
              SELECT    Curr.Customer,
                        ISNULL(Curr.Value, prev.Value) Value,
                        Curr.Dates,
                        Curr.RowNum
              FROM      CustCte curr
              INNER JOIN CleanCust prev ON curr.Customer = prev.Customer
                                           AND curr.RowNum = prev.RowNum + 1)

/* Update the base table using the result set from the recursive CTE */
    UPDATE trg
    SET Value = src.Value
    FROM    @Customers trg
    INNER JOIN CleanCust src ON trg.Customer = src.Customer
                                AND trg.Dates = src.Dates

/* Display the results */
SELECT * FROM @Customers
0
 

Author Closing Comment

by:dkilby
Comment Utility
thanks for the help
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
SQL Backup skipping a few tables 7 25
C# SQL BULK INSERT CLASS 5 33
Creating Alerts in sql sever 2 12
SQL Maintenance Plan 3 12
How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now