Solved

SQL Syntax Counter Needed

Posted on 2014-02-26
7
251 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 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
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 

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

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
SQL Server 2012 to SQL Server 2016 24 57
SQL syntax for max(date) 3 39
SQL Server 2012 and core licensing 5 32
first parameter x of the decimal (x, y) 1 30
Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
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
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.

710 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