Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6597889
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T18:16:01+00:00 2026-05-25T18:16:01+00:00

So I’ve got a database which maintains all of the data in it in

  • 0

So I’ve got a database which maintains all of the data in it in a history database, so that we can change the history date, and go back and look at old data. I need to write a query that adjusts the dates in these history tables for each table. Right now I’ve got it working as a cursor, but it takes several minutes to run, and I want to see if I can do it without a cursor.

Edit: To be clear, the primary keys that I’m pulling are the primary keys for the non-history tables. The history tables may have multiple entries for the single primary key. (Which is why the inner sql is doing the join that it is)

Here’s the cursor:

DECLARE tableID CURSOR FOR
SELECT
OBJECT_NAME(ic.OBJECT_ID) AS TableName,
COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.OBJECT_ID = ic.OBJECT_ID
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
and COL_NAME(ic.OBJECT_ID, ic.column_id) != 'RecordID'

DECLARE @currentTable varchar(100)
DECLARE @currentID varchar(100)
DECLARE @currSql varchar(max)
OPEN tableID

FETCH FROM tableID
INTO @currentTable, @currentID
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @currSql = 
'update t1
set t1.EndDate = t2.BeginDate
from hist.' + @currentTable + ' t1 inner join hist.' + @currentTable + ' t2
on t1.' + @currentID + ' = t2.' + @currentID + '
and t2.BeginDate = (select MIN(BeginDate) from hist.' + @currentTable + ' t
where t.BeginDate >= t1.EndDate and t.' + @currentID + ' = t1.' + @currentID + ')'
EXEC(@currSql)
FETCH FROM tableID
INTO @currentTable, @currentID
END
CLOSE tableID
DEALLOCATE tableID
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T18:16:02+00:00Added an answer on May 25, 2026 at 6:16 pm

    I find it very hard to believe that this runs slowly because it’s a cursor. You can make the cursor slightly more efficient by saying:

    DECLARE CURSOR tableID LOCAL STATIC READ_ONLY FORWARD_ONLY FOR ...
    

    …but I bet if you just print all those SQL commands, copy and paste them into a new window, and execute them manually, that it will still take a lot longer than you’d like. The speed is probably related to the amount of data you’re updating (or at least scanning), not because you’re using a cursor to generate the commands.

    You can generate these commands without explicitly using a cursor, but rather using the metadata tables to build a string, but this will still really use a cursor in the engine… the code is just a lot tidier. I’ll post an example shortly.

    First, just adding a sample of what the output of your query currently looks like, for say the id column on table1. To help illustrate my comment and how it might be very hard for this update to ever affect any rows:

    update t1
    set t1.EndDate = t2.BeginDate
    from hist.table1 t1 
    inner join hist.table1 t2
    on t1.id = t2.id
    and t2.BeginDate = (select MIN(BeginDate) from hist.table1 t
    where t.BeginDate >= t1.EndDate and t.id = t1.id);
    

    Perhaps you meant a much simpler query, like:

    update hist.table1 
    set EndDate = BeginDate
    where BeginDate >= EndDate;
    

    Or perhaps you meant to reference some other table in the subquery?

    Anyway assuming one of the above queries is really what you intend to execute, to generate the first query you could try:

    DECLARE @sql NVARCHAR(MAX) = N'';
    
    SELECT @sql += CHAR(13) + CHAR(10)
    + N'update t1
        set t1.EndDate = t2.BeginDate
        from hist.' + QUOTENAME(t.name) + ' AS t1 
        inner join hist.' + QUOTENAME(t.name) + ' AS t2
        on t1.' + QUOTENAME(c.name) + ' = t2.' + QUOTENAME(c.name) 
        + 'and t2.BeginDate = (select MIN(BeginDate) from hist.' 
        + QUOTENAME(t.name) + ' AS t where t.BeginDate > t1.EndDate and 
        t.' + QUOTENAME(c.name) + ' = t1.' + QUOTENAME(c.name) + ');'
    FROM sys.tables AS t
    INNER JOIN sys.indexes AS i
    ON t.[object_id] = i.[object_id]
    AND i.is_primary_key = 1
    INNER JOIN sys.index_columns AS ic
    ON t.[object_id] = ic.[object_id]
    INNER JOIN sys.columns AS c
    ON c.column_id = ic.column_id
    AND c.[object_id] = ic.[object_id]
    WHERE c.name <> 'RecordID'
    AND t.[schema_id] = SCHEMA_ID('hist');
    
    PRINT @sql;
    -- EXEC sp_executesql @sql;
    

    And for the second it is a lot simpler:

    DECLARE @sql NVARCHAR(MAX) = N'';
    
    SELECT @sql += CHAR(13) + CHAR(10) 
        + N'UPDATE hist.' + QUOTENAME(t.name) 
        + ' SET EndDate = BeginDate
        WHERE BeginDate > EndDate;' 
    FROM sys.tables AS t
    WHERE t.schema_id = SCHEMA_ID('hist');
    
    PRINT @sql;
    -- EXEC sp_executesql @sql;
    

    Note that I changed the >= to > since if it’s already = there’s no reason to update. And again, these assume that everything is in the hist schema and all primary keys are single column primary keys. Though I will state again that the first, longer version of the query is much more expensive (two extra clustered index seeks and a very expensive table spool operator) – while not achieving results that are any different, whatsoever, from the shorter version I posted.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've got a string that has curly quotes in it. I'd like to replace
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a text area in my form which accepts all possible characters from
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I have a jquery bug and I've been looking for hours now, I can't
I have a French site that I want to parse, but am running into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.