Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

SQL Syntax Counter Needed

Posted on 2014-02-26
7
Medium Priority
?
254 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 70

Accepted Solution

by:
Scott Pletcher earned 2000 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
 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

 

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 70

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

916 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