views:

166

answers:

3

In SQL Server, I have two fields, one is primary and has an identity (AN_ID) then I have another one that for legacy reasons (don't ask) has to be updated reflecting the AN_ID. Currently they have the exact same value. I was wondering if there are pure T-SQL query (no stored procedures) to make it auto incremente.

Thank you very much

Edit: I'm forced to SQL Server 2000

+4  A: 

If both fields can contain the same value, then you can use an insert trigger or a computed column (new in SQL 2005) to accomplish this.

EDIT: Something like this should work.

CREATE TRIGGER MyTable_AI ON MyTable
AFTER INSERT AS
    UPDATE MyTable
    SET OTHER_ID = AN_ID
    WHERE AN_ID IN (SELECT AN_ID FROM inserted);
Jamie Ide
I'd go with computed column - only has impact when doing a SELECT.
Randolph Potter
I completely forgot but I'm stuck with mssql 2000 :(
0plus1
Then use an AFTER INSERT trigger to set the 2nd field to the identity value in AN_ID.
Jamie Ide
+2  A: 

The second column could be a computed column with the formula AN_ID.

You could also create a view with an alias of AN_ID.

Gary W
+3  A: 

The "right" solution is almost certainly to use a trigger, however if that falls under the heading of "no stored procedures" then you can fudge things a little by running two consective queries (which you should be able to send as one query from your calling app - be useful to know what environment you're using on top of SQL Server).

e.g. (very roughly)

INSERT INTO tbl (col1, col2, col3) values (@col1param, @col2param, @col3param);
UPDATE tbl SET not_an_id = an_id WHERE an_id = SCOPE_IDENTITY()
Murph
I'm using php on top of this
0plus1
@@SCOPE_IDENTITY does not exist, use SCOPE_IDENTITY() instead
MaxiWheat