On Thu, 16 Dec 2010 09:48:08 -0800 (PST), fniles
<(E-Mail Removed)> wrote:
>I have a SQL Server 2005 table with an Identity column called ID, a
>Primary Key column called [Order], and an Account column like this:
>CREATE TABLE [dbo].[HistTradesOrig](
> [ID] [int] IDENTITY(1,1) NOT NULL,
> [order] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
>NULL,
> [Account] [varchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS
>NULL
>CONSTRAINT [DF_HistTradesOrig_Bill] DEFAULT ('0'),
> CONSTRAINT [PK__HistTradesOrig__52593CB8] PRIMARY KEY CLUSTERED
>(
> [order] ASC
>)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
>) ON [PRIMARY]
>
>I need to set [Order] to be a unique number containing account and
>another 6 digits number.
>Currently, most times I set [Order] = @ACCOUNT + '-' +
>convert(varchar(50),@ID) where @ID is the SCOPE_IDENTITY().
>Currently, this 6 digits number ranges from 100,000 to 999,999, and if
>it's possible we would like to keep it that way.
>The problem with that is since I have multiple thread doing it, every
>now and then I get Transaction Lock error.
>
>1. Is there any other way for me to set [Order] to be Account +
>another unique 6 digits number besides getting it from the Identity
>column of the same table ?
Hi fniles,
In addition to the suggestions I made in your other topics, here is
one more thought. Redesign the table as follows:
CREATE TABLE dbo.HistTradesOrig
(ID int IDENTITY(1,1) NOT NULL,
Account varchar(10) NOT NULL,
OrderNo int NOT NULL,
order AS Account + CAST(OrderNo AS char(6)),
-- Other columns,
PRIMARY KEY (ID),
UNIQUE (Account, OrderNo)
);
PS: I changed the Account column to be NOT NULL, since your
description implies that it obviously should be.
When inserting a new row, use this code:
INSERT INTO dbo.HistTradesOrig
(Account,
OrderNo,
...)
VALUES (@AccountID,
(SELECT COALESCE(MAX(OrderNo), 100000)
FROM dbo.HistTradesOrig
WHERE Account = @Account),
...);
Make sure to do this in a TRY ... CATCH block that handles the
theoretic possibility of a duplicate key insertion (in case there is a
race condition between two connections trying to isnert a row for the
same Account at the exact same time).
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog:
http://sqlblog.com/blogs/hugo_kornelis