Solved

SQL Syntax Counter Needed

Posted on 2014-02-26
7
244 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:
ScottPletcher 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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

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:ScottPletcher
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduced in Microsoft SQL Server 2005, the Copy Database Wizard (http://msdn.microsoft.com/en-us/library/ms188664.aspx) is useful in copying databases and associated objects between SQL instances; therefore, it is a good migration and upgrade tool…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

760 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

23 Experts available now in Live!

Get 1:1 Help Now