Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

SQL Syntax Counter Needed

Posted on 2014-02-26
7
Medium Priority
?
253 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 

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: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying 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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
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

705 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