Solved

SQL Syntax Counter Needed

Posted on 2014-02-26
7
247 Views
Last Modified: 2014-03-09
I have to update a counter field in one table while pulling the next counter number from another table and update that table. For example:

Table 1) SYSCNTRL has a field called INDXCNTR
Table 2) ITEMMSTR has item numbers and needs the next available INDXCNTR from SYSCNTRL. This field is also called INDXCNTR

So as I loop through records in ITEMSTR I need to get the value of SYSCNTRL.INDXCNTR and assign it to this record. Immediately afterward I need to increment the value of SYSCNTRL.INDXCNTR by one. Then I continue the process until all records are updated.

I have done this before with cursors but I am trying to move away from using cursors.
This is for SQL Server 2005.
0
Comment
Question by:rwheeler23
7 Comments
 
LVL 38

Expert Comment

by:Jim P.
ID: 39890837
I take it an identity column won't work for your purposes? That can auto-increment. Or a GUID Identity column is a pain in the nether regions.

I would suggest a custom function for this. But without details it is hard to give a straight out answer. Do you want  to break the ID out by state or region? Dates? Both?

For example the 15th order from Pennsylvania today  (57 ay of the year) might look like PA14057015. That gives you a detail  that order 00015 doesn't. So identifying that early makes sense as opposed trying do it later.
0
 
LVL 8

Expert Comment

by:Andrei Fomitchev
ID: 39891186
Table1 - master
Table2 - detail

Table1 ID int NOT NULL IDENTITY(1,1), ...

Table2 ..., Table1ID int, ... -- FK to Table1 (ID)

DECLARE @LatestID int

INSERT INTO Table1 (...) -- don't include ID
SET @LatestID = @@IDENTITY
INSERT INTO Table2 (...,Table1ID,...)
VALUES (..., @LatestID, ...)
0
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 500 total points
ID: 39893554
BEGIN TRY
BEGIN TRANSACTION
DECLARE @rows_updated int
UPDATE i
SET INDXCNTR = s.INDXCNTR + i_keys.row_num
FROM (
    SELECT key_col, /*key_col2, ... */
        ROW_NUMBER() OVER(ORDER BY key_col) AS row_num
    FROM dbo.ITEMMSTR
    --WHERE <conditions_indicating_INDXCNTR_needs_UPDATEd>
) AS i_keys
INNER JOIN dbo.ITEMMSTR i ON
    i.key_col = i_key.key_col
-- WITH (TABLOCKX) is required -- do NOT remove it!
CROSS JOIN dbo.SYSNCTRL s WITH (TABLOCKX)
SET @rows_updated = @@ROWCOUNT
UPDATE dbo.SYSNCTRL
SET INDXCNTR = INDXCNTR + @rows_updated
COMMIT TRANSACTION --this will release the TABLOCKX
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0
    ROLLBACK TRANSACTION
--...other error logic here...
END CATCH
END CATCH
0
NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

 

Author Comment

by:rwheeler23
ID: 39893733
I just got back into town and will take a look a these suggestions. The detail of the situation is this. I have a table with one record in it. This record will contain a company ID, a bunch of other columns, and a column that is an index to a note field. This field is defined as an integer. Every time a new item is added to inventory my application goes out and gets what the current value for the next index, assigns it to the item record just added and then increments by one to get ready for the next item insert. So I insert items into one table while I increment this index value in another table.

The problem I face right now is that I have been given an import file and I have to dump these items into the database and  bypass the application. I have already imported these items but now I need to populate the index value on each item with a unique incremented index value.

P.S. Every table in my database already has an identity column so that will not work.
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 39894893
If there is one row per company in the SYSNCTRL table, then you can very likely use:
WITH (ROWLOCKX)
rather than TABLOCKX.
0
 

Author Comment

by:rwheeler23
ID: 39895933
Excellent point! Your script will get tested this weekend.
0
 

Author Closing Comment

by:rwheeler23
ID: 39916188
Thank for another extremely useful tip.
0

Featured Post

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
SQL date incremented 11 31
migration MS SQL database to Oracle 30 61
SQL Server 2012 r2 - Varible Table 3 24
Insert query into temp tables using Coldfusion 3 21
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
I have a large data set and a SSIS package. How can I load this file in multi threading?
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
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

810 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