Autoincrement uniqueidentifier - sql-server

Basically I want to use uniqueidentifier in similar way as identity. I don't want to insert values into it, It should just insert values automatically, different value for each row.
I'm not able to set autoincrement on columns of type uniqueidentifier(the property 'autoincrement' is set to false and is not editable).

Or even better: use the newsequentialid() as the default for your UNIQUEIDENITIFER column. That'll give you a somewhat sequential series of GUIDs.
CREATE TABLE dbo.YourTable
(SerialID UNIQUEIDENTIFIER
CONSTRAINT DF_SerialID DEFAULT newsequentialid(),
.... (other columns)......
)
Trouble is: newsequentialid is only available as a column default - you cannot call it as a function or anything. But that seems to fit your requirements.
UPDATE: there appears to be an acknowledged bug in SQL Server Management Studio that prevents specifying newsequentialid() as the default for a column in the interactive table designer.
See: http://social.msdn.microsoft.com/Forums/en-US/sqltools/thread/cad8a4d7-714f-44a2-adb0-569655ac66e6
Workaround: create your table without specifying any default, and then type in this T-SQL statement in a normal query window and run it:
ALTER TABLE dbo.YourTable
ADD CONSTRAINT DF_SerialID DEFAULT newsequentialid() FOR SerialID
That should do the trick!

I guess you mean in SQLServer and not C#...
Set the column as PRIMARY KEY and ROWGUID
RowGuid http://img341.imageshack.us/img341/8867/sqlserverrowguid.png

I think
CREATE TABLE dbo.YourTable
(
SerialID UNIQUEIDENTIFIER PRIMARY KEY DEFAULT newsequentialid()
)
is simplier

Use NewID() as the default value. At least this is what you would do for SQL Server.

Related

Is it possible to insert timestamp in sql?

I want to have a column in which the default timestamp is added when an insertion is done. I have done that in MySQL using choosing default timestamp option. How do I do that in SQL Server?
ALTER TABLE table_name ADD InsertTime DATETIME DEFAULT GETDATE()
ALTER TABLE [table] ADD [CreationTimeStampUTC] DATETIME DEFAULT(GETUTCDATE())
Or you could do the same with GETDATE(), which I think I've seen more in real-world code. Note, of course, that GETDATE() will be valued with the current server time of the SQL Server, and may or may not match up with the current time of the web server if you have one, or particularly the client's machine. Obviously there's no issue with that, just make sure you're aware of the implications ahead of time. You could also store this timestamp as a DATETIMEOFFSET to rid yourself of some of those concerns, but since you're speaking explicitly of on-server default values, I think UTC is perfectly sufficient.
What you're looking for is a default constraint. How you add it depends on whether the column already exists or not. If it doesn't, you can add the column and the constraint in one shot like so:
alter table dbo.yourTable
add [NewColumn] datetime
constraint [DF_NewColumn] default (getdate());
If the column already exists, you can attach a default to it like so:
alter table dbo.yourTable
add constraint [DF_ExistingColumn] default (getdate()) for [ExistingColumn];
Finally, if the table doesn't yet exist, you can add the constraint to the table definition:
create table dbo.yourTable (
NewColumn datetime not null constraint [DF_NewColumn] default (getdate())
)
Note: in all cases, I gave the constraint a name. You can choose not to, but then you'll eventually get a huffy DBA asking why her database comparison is a mess because the constraint names don't match up between dev and prod. :)

TSQL (SQL Server 2005 and 2000) - Changing default and constraint of an existing column?

I am changing the type of a column from bit to tinyint. After that, I want to define the new default value and a new constraint for it. How do I do this? I know how to do it if the column does not exist, but for an existing column my approaches failed so far.
Thanks! :)
Try something like this:
-- change the column type
ALTER TABLE dbo.gradytest
ALTER COLUMN YourColumn TINYINT NULL
-- add a named default constraint
ALTER TABLE dbo.gradytest
ADD CONSTRAINT DF_YourColumn_Default DEFAULT(4) FOR YourColumn

how can I use GUID datatype in SQL Server 2008?

I want to build an employees table using SQL SERVER 2008 , and in my table I want to have an ID for each employee .
I heared about GUID and I kind of understood that its a data type , But I couldn't use it
could you please show me the way to use it ...
by the way , lets say I want something like this :
CREATE TABLE Employees (
ID guid PRIMARY KEY,
Name NVARCHAR(50) NOT NULL
)
How can I do it ?? because I want to benefit from it , but I couldn't find out how to do that
It's not called GUID in SQL Server. It's called uniqueidentifier
The type is called UNIQUEIDENTIFIER as others have pointed out already. But I think you absolutely must read this article before proceeding: GUIDs as PRIMARY KEYs and/or the clustering key
They are called uniqueidentifier
Don't use uniqueidentifier as primary key if clustered (which is the default for PKs)
Seriously: use a standard IDENTITY instead
You can also consider using NEWSEQUENCIALID as the default value for your ID column as it would be faster than using NEWID() generate the GUIDs.
BUT (from the same link above):-
If privacy is a concern, do not use this function. It is possible to guess the value of the next generated GUID and, therefore, access data associated with that GUID.
Practical demo, FWIW
DECLARE #guid1 AS uniqueidentifier
SET #guid1 = NEWID()
SELECT #guid1
The GUID in sql server is known by UNIQUEIDENTIFIER data type. below is the desired code.
CREATE TABLE Employees
(
Id UNIQUEIDENTIFIER PRIMARY KEY,
Name NVARCHAR (50) not null
)
GO

using NEWSEQUENTIALID() with UPDATE Trigger

I am adding a new GUID/Uniqueidentifier column to my table.
ALTER TABLE table_name
ADD VersionNumber UNIQUEIDENTIFIER UNIQUE NOT NULL DEFAULT NEWSEQUENTIALID()
GO
And when ever a record is updated in the table, I would want to update this column "VersionNumber". So I create a new trigger
CREATE TRIGGER [DBO].[TR_TABLE_NAMWE]
ON [DBO].[TABLE_NAME]
AFTER UPDATE
AS
BEGIN
UPDATE TABLE_NAME
SET VERSIONNUMBER=NEWSEQUENTIALID()
FROM TABLE_NAME D
JOIN INSERTED I ON D.ID=I.ID/* some ID which is used to join*/
END
GO
But just realized that NEWSEQUENTIALID() can only be used with CREATE TABLE or ALTER TABLE. I got this error
The newsequentialid() built-in function can only be used in a DEFAULT expression for a column of type 'uniqueidentifier' in a CREATE TABLE or ALTER TABLE statement. It cannot be combined with other operators to form a complex scalar expression.
Is there a workaround for this ?
Edit1: Changing NEWSEQUENTIALID() to NEWID() in the trigger solves this, but I am indexing this column and using NEWID() would be sub-optimal
As you say its only available under certain conditions, you could do something nasty like:
DECLARE #T TABLE (G UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID())
INSERT #T OUTPUT INSERTED.G VALUES (DEFAULT)
Does it have to be a GUID? if you use a rowversion you get the same functionality without needing a trigger as well as better indexing performance.

Force default value when adding column to table - SQL Server

In SQL Server 2000/2005,
Is it possible to force the default value to be written to already existing rows when adding a new column to a table without using NOT NULL on the new column?
You need two statements. First create the column with not null. Then change the not null constraint to nullable
alter table mytable add mycolumn varchar(10) not null default ('a value')
alter table mytable alter column mycolumn varchar(10) null
I understand your question, but you are saying that for future records, NULL (unknown, indeterminate or whatever your semantics are) is acceptable (but if it is left off in an insert, there will be a default), but that for all the existing data, you are going to go ahead and assign it the default.
I would have to look hard at this situation and ask why you are even going to allow NULLs in future records at all - given none of the historical records will have it, and there is a default in place for future records.
I doubt it.
http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx
The approach recommended by Microsoft is as follows (taken from the url above)
UPDATE MyTable SET NullCol = N'some_value' WHERE NullCol IS NULL
ALTER TABLE MyTable ALTER COLUMN NullCOl NVARCHAR(20) NOT NULL
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}
[**WITH VALUES]**
WITH VALUES can be used to store the default value in the new column for each existing row in the table.
more detail on MSDN link .
https://msdn.microsoft.com/en-in/library/ms190273.aspx

Resources