default column value - sql

i'm trying to have a table with a column that has a default value.
right now i can only get this by having a trigger change the value to the default, is it possible to have it declared on the table right from the start?
Would it be possible to have something like the Identity, where i don't have to pass the value into the insert?
egx: insert into Direct values(2)
and the table would become
id | item
1 | 2
the id = 1, would be the deafult value
thanks in advance!

you can create constraints at time of table creation or later.
create table
#test
(
id int identity(1,2),
name char(255) default newid(),
code int default 2
)
---if a table contains all default values,you can insert like below
insert into #test
default values
updated as per comments:
create table
#test1
(
id int identity(1,2),
name char(255) default newid(),
code int default 2,
notdf int
)
---if a table contains one default value and rest all are default
insert into #test1(notdf)
select 2
Further if you want to add a default value after table creation you can do it like below
create table
tt1
(
valuue int,
address char(2) not null
)
insert into tt1
select 1,'a'
ALTER TABLE tt1 ADD CONSTRAINT test1 DEFAULT null FOR address;

Use default. You can change an existing column by doing:
ALTER TABLE t ADD CONSTRAINT df_t_column DEFAULT 1 for id;
An identity is trickier. I would suggest copying the data over to a temporary table, dropping the table, creating it with an identity column and reloading the data.

Related

SQL Server Insert with no specified columns

I have a table with an auto-generated ID column (and that's all!)
CREATE TABLE [dbo].[EmailGroup](
[EmailGroupGuid] [uniqueidentifier] NOT NULL
CONSTRAINT [PK_EmailGroup] PRIMARY KEY CLUSTERED ([EmailGroupGuid] ASC)
) ON [PRIMARY]
ALTER TABLE [dbo].[EmailGroup]
ADD CONSTRAINT [DF_EmailGroup_EmailGroupGuid] DEFAULT (newsequentialid()) FOR [EmailGroupGuid]
I want to INSERT into this table and extract the generated ID. but, I can't work out if it's possible. It seems to complain about the lack of values/columns.
DECLARE #Id TABLE (Id UNIQUEIDENTIFIER)
INSERT INTO EmailGroup
OUTPUT inserted.EmailGroupID INTO #Id
Is there any way to do this? I mean I could add a dummy column to the table and easily do this:
INSERT INTO EmailGroup (Dummy)
OUTPUT inserted.EmailGroupID INTO #Id
VALUES (1)
however I don't really want to.
I could also specify my own ID and insert that, but again, I don't really want to.
Though I'm not sure why would you need such a table, the answer to your question is to use the keyword DEFAULT:
INSERT INTO EmailGroup (EmailGroupGuid)
OUTPUT inserted.EmailGroupGuid INTO #Id
VALUES(DEFAULT);
Another option is to use DEFAULT VALUES, as shown in Pawan Kumar's answer.
The key difference between these two options is that specifying the columns list and using the keyword default gives you more control.
It doesn't seem much when the table have a single column, but if you will add columns to the table, and want to insert specific values to them, using default values will no longer be a valid option.
From Microsoft Docs on INSERT (Transact-SQL):
DEFAULT
Forces the Database Engine to load the default value defined for a column.
If a default does not exist for the column and the column allows null values, NULL is inserted.
For a column defined with the timestamp data type, the next timestamp value is inserted.
DEFAULT is not valid for an identity column.
DEFAULT VALUES
Forces the new row to contain the default values defined for each column.
So as you can see, default is column based, while default values is row based.
Please use this.
CREATE TABLE [dbo].[EmailGroup]
(
[EmailGroupGuid] [uniqueidentifier] NOT NULL CONSTRAINT [PK_EmailGroup] PRIMARY KEY CLUSTERED ([EmailGroupGuid] ASC)
) ON [PRIMARY]
ALTER TABLE [dbo].[EmailGroup]
ADD CONSTRAINT [DF_EmailGroup_EmailGroupGuid] DEFAULT (newsequentialid()) FOR [EmailGroupGuid]
DECLARE #Id TABLE (Id UNIQUEIDENTIFIER)
INSERT INTO EmailGroup
OUTPUT inserted.EmailGroupGuid INTO #Id DEFAULT VALUES
SELECT * FROM #Id
last 3 OUTPUTs from my Laptop
--92832040-7D52-E811-B049-68F728AE8695
--2B6ADC5F-7D52-E811-B049-68F728AE8695
--0140AF66-7D52-E811-B049-68F728AE8695

generate sequence in sql server 2014

I am trying to generate a sequence varchar text type, but I do not want to have to create another column to get the id to format it and insert it I want to generate it in the same column, help
create table tbl (
Id int identity not null,
CusId as 'CUS' + format(Id, '00000'),
-- ...
)
You can use sequence object that appeared in SQL Server 2012 + default value like this:
create sequence dbo.ids as int
minvalue 1;
create table dbo.tbl (
CusId varchar(100) default 'CUS' + format(NEXT VALUE FOR dbo.ids, '00000'));
insert into dbo.tbl (CusId) default values;
insert into dbo.tbl (CusId) default values;
insert into dbo.tbl (CusId) default values;
select *
from dbo.tbl;
-----
--CusId
--CUS00001
--CUS00002
--CUS00003
Believe the only viable solution is using 2 columns as you mentioned, and discussed here:
Autoincrement of primary key column with varchar datatype in it
Have not seen it achieved in a single column on its own.

CREATE TABLE where multiple columns are inserted with same value

Lets say I have a CREATE TABLE code like this:
CREATE TABLE Test (
ID int NOT NULL IDENTITY(1,1),
SortIndex int,
Name nvarchar(50) NOT NULL
);
I was wondering if it's possible to make a table in MSSQL which had the ability to insert the ID's value into the SortIndex column when I run an INSERT.
So I would run this INSERT:
INSERT INTO Test (Name) VALUES ('Awesome Dude');
Which would normally yield the row:
ID,SortIndex,Name
1,NULL,"Awesome Dude"
But I'd like it to automatically be:
ID,SortIndex,Name
1,1,"Awesome Dude"
Is this even possible by altering the CREATE TABLE script, or do I have to use a TRIGGER?
I would be inclided to take a slightly different approach to this. If you want your SortIndex to default to the ID, but be overridable, I would use a nullable column, and a computed column:
CREATE TABLE Test (
ID int NOT NULL IDENTITY(1,1),
OverrideSortIndex int,
Name nvarchar(50) NOT NULL,
SortIndex AS ISNULL(OverrideSortIndex, ID)
);
If you need to change the sort index for any reason, update the column OverrideSortIndex and this takes precedence.

SQL Server Database unique number generation on any record insertion

I have like 11 columns in my database table and i am inserting data in 10 of them. i want to have a unique number like "1101 and so on" in the 11th column.
Any idea what should i do?? Thanks in advance.
SQL Server 2012 and above you can generate Sequence
Create SEQUENCE RandomSeq
start with 1001
increment by 1
Go
Insert into YourTable(Id,col1...)
Select NEXT VALUE FOR RandomSeq,col1....
or else you can use Identity
Identity(seed,increment)
You can start the seed from 1101 and increment the sequence by 1
Create table YourTable
(
id INT IDENTITY(1101,1),
Col varchar(10)
)
If you want to have that unique number in a different field then you can manipulate that field with primary key and insert that value.
If you want in primary key value, then open the table in design mode, go to 'Identity specification', set 'identity increment' and 'identity seed' as you want.
Alternatively you can use table script like,
CREATE TABLE Persons
(
ID int IDENTITY(12,1) PRIMARY KEY,
FName varchar(255) NOT NULL,
)
here the primary key will start seeding from 12 and seed value will be 1.
If you have your table definition already in place you can alter the column and add Computed column marked as persisted as:
ALTER TABLE tablename drop column column11;
ALTER TABLE tablename add column11 as '11'
+right('000000'+cast(ID as varchar(10)), 2) PERSISTED ;
--You can change the right operator value from 2 to any as per the requirements.
--Also replace ID with the identity column in your table.
create table inc
(
id int identity(1100,1),
somec char
)

When we create a table how to tall SQLITE to set default value of datetime to `now`?

We have something like:
CREATE TABLE IF NOT EXISTS files
(encoded_url varchar(65) UNIQUE NOT NULL primary key, modified DATETIME NOT NULL);
We want each time a new record is created to fill its modified field with now time automatically. Can we tall SQLite that it has to do such thing when we create a table or we should always insert nowwhen we fill in a row?
You can use default CURRENT_TIMESTAMP in the column specification:
sqlite> create table t (a datetime default CURRENT_TIMESTAMP, b text);
sqlite> insert into t(b) values ('hello');
sqlite> select * from t;
2011-10-16 17:29:54|hello
sqlite> insert into t(b) values ('hello again');
sqlite> select * from t;
2011-10-16 17:29:54|hello
2011-10-16 17:30:04|hello again
There are other date/time options, documented in the column definition part of the create table syntax docs.
CREATE TABLE IF NOT EXISTS files
(encoded_url varchar(65) UNIQUE NOT NULL primary key, modified DEFAULT (datetime('now','localtime')) NOT NULL);