January 17, 2010 at 11:11 pm
Hi...
how can I get uniqueidentifier value as return after insert a record.
January 18, 2010 at 12:32 am
Hi,
use the trigger to get the newid value
create table MYTABLE
(
col1 int,
col2 varchar (2)
)
CREATE trigger ins_trg_MYTABLE on MYTABLE
for INSERT
as
PRINT CONVERT(varchar(255), newid())
return
insert into MYTABLE
select 1,'A'
January 18, 2010 at 1:13 am
Hi
I am trying to understand your scenario...
Why do you require the newid() to be printed in the trigger?
January 18, 2010 at 1:19 am
Hi,
Because the OP needs to get the unique identifier in every row insert!!!
January 19, 2010 at 8:04 am
It depends on a lot of things, please post more info on exactly what you are trying to achieve including table structures, example data.
Do you want to use a stored procedure?
Do you want the new id returned in an output parameter or as a result set?
This is just one way using a stored proc:
CREATE TABLE testTable1
(
id uniqueidentifier,
name varchar(50)
)
GO
CREATE PROCEDURE procTestTableInsert
(
@name varchar(50)
)
AS
DECLARE @id uniqueidentifier
SELECT @id = NEWID()-- Get a new unique identifier to insert
INSERT
testTable1(id,name)
VALUES
(@id,@name)
SELECT @id-- 'Return' the inserted uniqueidentifier as a 1 row 1 column result set
GO
--== Do the insert
EXEC procTestTableInsert 'Fred'
--== CLEAN UP
DROP TABLE testTable1
GO
DROP PROCEDURE procTestTableInsert
GO
July 2, 2018 at 9:29 pm
Try this:
DECLARE @id varchar(50) = CONVERT(VARCHAR(50), NEWID());
INSERT INTO [yourtable] ( [id]) VALUES (@id);
SELECT @id;
July 3, 2018 at 6:52 am
if you are wanting to return the identity of the insert perhaps to use as a foreign key in another insert
create table x1 (id int identity(1,1),col2 varchar(100))
declare @id int
insert into x1 select NEWID()
set @id=SCOPE_IDENTITY()
select @id
***The first step is always the hardest *******
July 3, 2018 at 8:22 am
dastagiri16 - Sunday, January 17, 2010 11:11 PMHi... how can I get uniqueidentifier value as return after insert a record.
Could you post a better question?
Are you looking for something like this?
CREATE TABLE [dbo].[Sample] (
SampleId UNIQUEIDENTIFIER DEFAULT NEWID() PRIMARY KEY NONCLUSTERED
, SampleData VARCHAR(32)
);
DECLARE @PKeys TABLE (PKey UNIQUEIDENTIFIER);
INSERT INTO [dbo].[Sample]([SampleData])
OUTPUT [Inserted].[SampleId] INTO @PKeys([PKey])
VALUES ('Sample1'),('Sample2'),('Sample3');
SELECT * FROM [dbo].[Sample] AS ;
SELECT * FROM @PKeys AS [pk];
DROP TABLE [dbo].[Sample];
July 5, 2018 at 4:06 am
NB. This is an 8 year old post
Viewing 10 posts - 1 through 10 (of 10 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy