views:

36

answers:

3

Example:

IF OBJECT_ID('T1') IS NOT NULL
DROP TABLE T1;
GO

CREATE TABLE T1 (id int PRIMARY KEY, timestamp);
GO

INSERT INTO T1(id) VALUES (1);
GO

declare @v timestamp;
INSERT INTO T1(id) OUTPUT inserted.timestamp as v VALUES (10);
select @v

How can I get the inserted.timestamp into variable @v?

A: 

One way would be to use identity:

declare @v timestamp; 
declare @ID int; 
INSERT INTO T1(id) OUTPUT inserted.timestamp as v VALUES (10); 
select @ID =@@IDENTITY;
select @v=timestamp from T1 where id=@ID;

(edit)... of course that would require an identity column. Since you know the value of the ID you are inserting then you don't even need to do this, just select the same row after you insert it using your original value.

Is the point you would like to do this all in a single statement? You could probably do it with a trigger but seems unnecessary.

jamietre
Thanks. However, I want to reduce an extra select from the table to reduce the overhead. The result is already available as "v" in the INSERT INTO statement, and I only need to get it out so I can return it (for example if this is implemented in a stored-procedure)
Jacky Chen
How about creating the timestamp yourself instead of using a timestamp column? e.g. select @ts=GETDATE(); insert into t1(id,timestamp) values (10,@ts); SELECT @ts;
jamietre
@jamietre: if ever, then using `SCOPE_IDENTITY()` instead of @@identity.... Plus - the OP is *not* using `IDENTITY` in his table - rather, he's actually defining the value to be stored... just used that value to retrieve the `timestamp`
marc_s
@marc_s. I realized that, hence my edit. You are correct about scope_identity(). Old habits die hard.
jamietre
@jamietre - in SQL Server a timestamp column has nothing to do with dates.
HLGEM
Right. I was proposing a different approach.
jamietre
A: 

Well, you're inserting a specific value into the ID column, which is the primary key - so just read out the row once you've inserted it...

INSERT INTO T1(id) VALUES (1);
GO

DECLARE @v timestamp

SELECT @v = TIMESTAMP 
FROM dbo.T1 
WHERE ID = 1

SELECT @v
marc_s
+1  A: 

This is what I got to work:

IF OBJECT_ID('T1') IS NOT NULL 
DROP TABLE T1; 
GO 

CREATE TABLE T1 (id int PRIMARY KEY, timestamp); 
GO 

INSERT INTO T1(id) VALUES (1); 
GO 

declare @v as table ([timestamp] varbinary) --timestamp; 
INSERT INTO T1(id) 
OUTPUT inserted.[timestamp] into @v 
VALUES (10); 

select * from @v 

One thing you need to realize is a timestamp field cannot be manually populated. So you must use some other type in your output table. ANd BTW timestamp is deprecated, I would not use it in new development at all. Use rowversion instead. And timestamp doesn't mean it will be a date for those who think it should be like the ANSII Standard, IN SQL Server it is not a date or convertable to a date.

HLGEM