Get last inserted UNIQUEIDENTIFIER in SQL Server 2000 - sql-server-2000

The OUTPUT clause is compatible with SQL Server 2005 but not SQL Server 2000.
How do I convert this command to work in SQL Server 2000?
CREATE TABLE sample
(
ID uniqueidentifier NOT NULL DEFAULT newid(),
Title varchar(30) NOT NULL
)
INSERT INTO sample (Title)
OUTPUT INSERTED.ID
VALUES ('Test1')
I need the command to retrieve the ID since the INSERT command needs to be called from a stored procedure.
Thanks for any help!

DECLARE #uid uniqueidentifier
SET #uid = newid()
INSERT INTO sample (ID, Title)
VALUES (#uid,'Test1')
SELECT #uid AS ID

Related

SQL Server : trigger on Insert alter input

I am fairly new to SQL Server and I am struggling with creating a trigger that does what I need.
We have a table that before a record is inserted we want to manipulate the input value.
Example table:
MyTable
(
[RUID] INT IDENTITY(1,1),
[CustomerName] nvarchar(200),
[CustomerStatus] INT,
[CustomerType] char(1),
[OtherFields] nvarchar(100)
)
An insert may come in like:
INSERT INTO MyTable ([CustomerName], [CustomerStatus], [CustomerType], [OtherFields])
VALUES ('LName~FName', 2, 'A', 'Other Info')
We don't have control of the source system doing the insert (a vendor product that is on its way out in a couple years so management doesn't want to spend the sums of money to have them alter it) but we need something like this to happen.
CustomerStatus that is inserted to be 2x inserted value
CustomerType - Regardless of the value sent we want to be overridden with a value of 'B'
All other columns are left as is.
So with an insert sent with the values in the example above, we would actually want this to end up in the table:
'LName~FName', 4, 'B', 'Other Info'
Any help you could provide would be greatly appreciated.
Specs:
SQL Server 2008 R2 Standard Edition (Database is in SQL Server 2000 compatibility mode though)
You basically need an Instead of trigger. The code would look something like...
CREATE TRIGGER tr_Insert_MyTable
ON MyTable
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO MyTable ([CustomerName], [CustomerStatus], [CustomerType], [OtherFields])
SELECT [CustomerName]
, [CustomerStatus] * 2 AS [CustomerStatus]
,'B' [CustomerType]
, [OtherFields]
FROM inserted
END

Updating a Table after some values are inserted into it in SQL Server 2008

I am trying to write a stored procedure in SQL Server 2008 which updates a table after some values are inserted into the table.
My stored procedure takes the values from a DMV and stores them in a table. In the same procedure after insert query, I have written an update query for the same table.
Insert results are populated fine, but the results of updates are getting lost.
But when I try to do only inserts in the stored procedure and I execute the update query manually everything is fine.
Why it is happening like this?
there should not be a problem in this.
below code working as expected.
create procedure dbo.test
as
begin
create table #temp (
name varchar(100) ,
id int
)
insert #temp
select name ,
id
from master..sysobjects
update #temp
set name='ALL Same'
from #temp
select * from #temp
drop table #temp
end
go
Best approach is to use Trigger, sample of AFTER UPDATE trigger is below:
ALTER TRIGGER [dbo].[tr_MyTriggerName]
ON [dbo].[MyTableName] AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
--if MyColumnName is updated the do..
IF UPDATE (MyColumnName)
BEGIN
UPDATE MyTableName
SET AnotherColumnInMyTable = someValue
FROM MyTableName
INNER JOIN Inserted
ON MyTableName.PrimaryKeyColumn = Inserted.PrimaryKeyColumn
END
END

Insert results of execute(#QueryString) into a table while adding an extra column

I am writing a stored procedure that dynamically creates a SQL string, #SQLQuery. After I create this query, I need to execute the query and insert it into a table in the database while adding another column that specifies a unique ID for this particular insert. (Context: It is possible in this application that multiple groupings of data will be inserted into this table and I need to be able to differientiate between groupings at a later date. )
This issue is similar to this question except I am using Microsoft SQL Server 2008 instead of mysql. I have tried the solution there:
INSERT INTO data_table_name
EXECUTE(#SQLQuery), #SomeID
but MS SQL Server 2008 doesn't like that syntax.
Any ideas on how to do this in SQL Server 2008?
You can store query result in table variable and then read from that with extra column and write to final table
DECLARE #temp table (col1 int, col2 varchar(10), ....)
INSERT INTO #temp
EXEC(#SQLQuery)
INSERT INTO data_table_name
SELECT *, #SomeID FROM #temp
You can also append #SomeID in your dynamic sql string.
Example:
SET #SQLQuery = 'SELECT *,' + #SomeID + ' FROM ' + #tableNameVar
and then do this
INSERT INTO data_table_name
EXECUTE(#SQLQuery)
Since you mentioned you are doing this in a Stored Procedure, what I would suggest is for you to:
Execute the #SQLQuery first;
Upon successful execution of the #SQLQuery, insert the #SQLQuery to the table with the unique ID.
i.e.
EXEC sp_executesql #SQLQuery, #Param
IF ##ERROR <> 0
BEGIN
INSERT INTO TableA(Query)
VALUES(#SQLQuery)
END
You're better off designing TableA such that the ID will be an Identity so that a unique sequential ID is generated when you insert a record into that table.

SQL Server 2008. Difficulty in setting date and time "timestamp"

I am using MS SQL Server 2008 R2 and I need to have a cell in each row with the date and time of when the row was inserted in the database. Now as I want to script and then load the database in MS SQL Server 2005 I Cannot use datetime or date so I tried to use getdate() function in the Computed Column Specification property. Can anyone please help me.
Thanks
Jean Claude, here is a complete example.
Code
USE tempdb;
SET NOCOUNT ON;
GO
CREATE TABLE dbo.TestTable (
RecordId int IDENTITY,
RecordValue varchar(32) NOT NULL,
RecordCreateDate datetime NOT NULL,
CONSTRAINT PK_TestTable
PRIMARY KEY CLUSTERED (
RecordId
)
)
GO
ALTER TABLE dbo.TestTable
ADD CONSTRAINT DF_TestTable_RecordCreateDate
DEFAULT GETDATE()
FOR RecordCreateDate;
GO
INSERT INTO dbo.TestTable (RecordValue) VALUES ('this');
WAITFOR DELAY '00:00:01';
INSERT INTO dbo.TestTable (RecordValue) VALUES ('that');
WAITFOR DELAY '00:00:01';
INSERT INTO dbo.TestTable (RecordValue) VALUES ('the other thing');
SELECT * FROM dbo.TestTable;
Results
RecordId RecordValue RecordCreateDate
-------- --------------- -----------------------
1 this 2012-05-16 10:43:48.400
2 that 2012-05-16 10:43:49.403
3 the other thing 2012-05-16 10:43:50.403
You should also research the new datetime data types and the SYSDATETIME() function.
Jean Claude, you seem to be under a misapprehension about datetime, which has been supported in every version of SQL Server I've ever used, all the way back to 6.5. It's the Date and Time types that are new in SQL 2008.
Rob's excellent answer should work fine in both SQL 2005 and 2008.

SQL Server: How do I get the value for the row I inserted?

My SQL Server table has, between other, these columns.
AutoID which has IdentitySpecification set to True and GuidKey which has the default value of (newid())
AutoID GuidKey
1 f4rc-erdd
2 gedd-rrds
Is there any way of getting the GuidKey from the row inserted?
I need something like the Scope_Identity(), with the difference that i don't want to get the content of AutoID, but the GuidKey column.
Sql Server 2005/2008
INSERT INTO myTable (SomeColumn)
OUTPUT INSERTED.GuidKEY
VALUES ('SomeData')
Sure:
SELECT GuidKEy FROM [Table] WHERE AutoID= scope_identity()
You can do the following:
DECLARE #TempTable TABLE (GuidKey UNIQUEIDENTIFIER)
INSERT INTO YourTable(Columns)
OUTPUT INSERTED.GuidKey INTO #TempTable(GuidKey)
VALUES(YourVALUES)
This will insert the inserted GuidKey into #TempTable. You can then pull the value from that table.
For the uniqueidentifier i do as follows:
DECLARE #ID uniqueidentifier
SET #ID = newId()
...
Then i use the #ID in my insert statement. Finally i return the value using SELECT #ID or RETURN #ID