Adding a SQL Default value of 01 to a database column - sql

How do you add the following default value to a sql database table?
01
I have tried various datatypes but the 0 keeps disappearing. I haven't even been able to find an example on the exchange or google but I assume this is very straight forward and I am being a numpty!!!
I have tried numeric/integer/varchar without luck. Thanks.

create table MyTable (Id int, Value varchar(100) not null default('01'))
Insert into MyTable (Id) values (1)
Select Value
From MyTable
will be '01'
Sql fiddle

Another option could be:
Open your Table Designer and you will see something like this:
If you prefer code:
USE ["name of your dataBase"]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Table_1](
[id] [int] IDENTITY(1,1) NOT NULL,
[sample02] [nvarchar](50) NOT NULL,
[sample03] [nvarchar](50) NULL,
CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ON [PRIMARY]
GO
ALTER TABLE [dbo].[Table_1] ADD CONSTRAINT [DF_Table_1_sample02] DEFAULT ('01') FOR [sample02]
GO
And finally, you can visit this Microsoft post: Specify Default Values for Columns

Related

Violation of PRIMARY KEY constraint even though i use proper indexes and query scheme

I have several unique indexes. For example
SET ansi_nulls ON
go
SET quoted_identifier ON
go
CREATE TABLE [dbo].[tblrelatedwords]
(
[cl_orgwordid] [BIGINT] NOT NULL,
[cl_relatedwordid] [BIGINT] NOT NULL,
[cl_relatedwordtypecode] [SMALLINT] NOT NULL,
[cl_relation_sourceid] [TINYINT] NOT NULL,
CONSTRAINT [PK_tblSeeAlso] PRIMARY KEY CLUSTERED ( [cl_orgwordid] ASC,
[cl_relatedwordid] ASC, [cl_relatedwordtypecode] ASC )WITH (pad_index = OFF
, statistics_norecompute = OFF, ignore_dup_key = OFF, allow_row_locks = on,
allow_page_locks = on, FILLFACTOR = 90) ON [PRIMARY]
)
ON [PRIMARY]
go
ALTER TABLE [dbo].[tblrelatedwords]
ADD CONSTRAINT [DF_tblSeeAlso_cl_RelatedWordTypeCode] DEFAULT ((255)) FOR
[cl_RelatedWordTypeCode]
go
When i use below query systematic even though i check with If not exists, i am still getting the below error
IF NOT EXISTS
( SELECT 1
FROM tblRelatedWords
WHERE (cl_OrgWordId=#cl_OrgWordId
AND cl_RelatedWordId=#cl_RelatedWordId
AND cl_RelatedWordTypeCode=#cl_RelatedWordTypeCode)
OR (cl_OrgWordId=#cl_RelatedWordId
AND cl_RelatedWordId=#cl_OrgWordId
AND cl_RelatedWordTypeCode=#cl_RelatedWordTypeCode) ) BEGIN
INSERT INTO tblRelatedWords
VALUES (#cl_OrgWordId,
#cl_RelatedWordId,
#cl_RelatedWordTypeCode,
#cl_Relation_SourceId) END
Error
Violation of PRIMARY KEY constraint 'PK_tblSeeAlso'. Cannot insert duplicate key in object 'dbo.tblRelatedWords'. The duplicate key value is (11439364, 2495501, 243). The statement has been terminated.
Yes multiple threads are adding to the same table however aren't IF NOT EXISTS supposed to prevent such cases?
Microsoft SQL Server 2016 (SP1-CU2) (KB4013106) - 13.0.4422.0 (X64)

SQL Server - How make allow NULL value in column

I'm newbie level in SQL Server
I want to allow null value in column, but it can't save.
So I will re-create a new table with same structure.
Please your help to allow null value in column with SQL script.
Thank you..
It looks as though the designer is trying to re-create the whole table and warning you about that.
It is possible to allow it to do so by disabling the option specified in the error message to "prevent saving changes that require the table to be recreated" but there is no need for this here.
You can just run
ALTER TABLE SAMPLE_UPL
ALTER COLUMN KORESKI VARCHAR(300) NULL
Or simply
ALTER TABLE SAMPLE_UPL
ALTER COLUMN KORESKI VARCHAR(300)
(as altering an existing column always sets it to allow NULL unless explicitly specified otherwise)
go in table design and checked check box this can allow you null values
script of this table
CREATE TABLE [dbo].[AWBuildVersion](
[SystemInformationID] [tinyint] IDENTITY(1,1) NOT NULL,
[Database Version] [nvarchar](25) NULL,
[VersionDate] [datetime] NOT NULL,
[ModifiedDate] [datetime] NOT NULL,
CONSTRAINT [PK_AWBuildVersion_SystemInformationID] PRIMARY KEY CLUSTERED
(
[SystemInformationID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

WRONG ERROR: Cannot insert explicit value for identity column in table 'Table1' when IDENTITY_INSERT is set to OFF

I have this weird problem, I have created a table with four column, and set one column as primary key with int type. I DID NOT set the primary key column as identity, but when I try to insert data in the table I get this error:
Cannot insert explicit value for identity column in table 'Table1' when IDENTITY_INSERT is set to OFF.
I tried to insert without specifying the primary key column (assuming it IS set to IDENTITY(x,y)!), in this this case it doesn't gives any error, but it doesn't insert any data neither!
creating the 'table1':
USE [NEWVEDJA]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Table1](
[id] [int] NOT NULL,
[name] [nvarchar](50) NULL,
[code] [int] NULL,
[exp_1] [nvarchar](max) NULL,
CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
and inserting into 'table1'
INSERT INTO [PARTIAL_NEWVEDJA].[dbo].[Table1]
([id]
,[name]
,[code]
,[exp_1])
VALUES
(1,N'سازمان',null,null), (2,N'معاونت',null,null);
GO
thanks a lot in advance.
USE [NEWVEDJA]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE....
With this code, the table is created with ID as PK without the IDENTITY property. All is well.
INSERT INTO [PARTIAL_NEWVEDJA].[dbo].[Table1]
([id]
With this code, you are inserting data into [PARTIAL_NEWVEDJA].[dbo].[Table1], which is a table in another DB. Looks like IDENTITY property is enabled in that table for ID column.
Can you try inserting data into the same table that you have created with your CREATE statement?
Raj
If identity_insert is disabled you will not be allowed to explicitly set values for the id column. I'm assuming some sort of autonumber is established.
Try:
INSERT INTO [PARTIAL_NEWVEDJA].[dbo].[Table1]
([id]
,[name]
,[code]
,[exp_1])
VALUES
(null,N'سازمان',null,null), (2,N'معاونت',null,null);

How to create two or more Unique Columns in SQL Azure?

I want to select two columns in my table and make them unique but I don't know how to do it in SQL Azure database. As you can see in the image below, it doesn't show any option to modify the table properties, so everything is done using sql queries:
Here is the generated script of the table:
USE [mydbase]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[clientaccess](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[ModuleName] [nvarchar](50) NOT NULL,
[ClientAuthenticationId] [bigint] NOT NULL,
[HasAccess] [bit] NOT NULL,
CONSTRAINT [PK_clientaccess_ID] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
GO
ALTER TABLE [dbo].[clientaccess] WITH CHECK ADD CONSTRAINT [CAI_caID] FOREIGN KEY([ClientAuthenticationId])
REFERENCES [dbo].[clientauthentication] ([ID])
GO
ALTER TABLE [dbo].[clientaccess] CHECK CONSTRAINT [CAI_caID]
GO
This is the preview where I encountered the problem, it contains duplicate records:
Hope someone understand my explanation.
Sometimes GUIS have limitations (or not but you haven't discovered yet how all functionalities work). You can always add a unique constraint with ALTER TABLE:
ALTER TABLE [dbo].[clientaccess]
ADD CONSTRAINT Module_Client_UQ --- choose a name
UNIQUE (ModuleName, ClientAuthenticationId) ;

SQL Server equivalent to MySQL enum data type?

Does SQL Server 2008 have a a data-type like MySQL's enum?
It doesn't. There's a vague equivalent:
mycol VARCHAR(10) NOT NULL CHECK (mycol IN('Useful', 'Useless', 'Unknown'))
The best solution I've found in this is to create a lookup table with the possible values as a primary key, and create a foreign key to the lookup table.
IMHO Lookup tables is the way to go, with referential integrity.
But only if you avoid "Evil Magic Numbers" by following an example such as this one:
Generate enum from a database lookup table using T4
Have Fun!
CREATE FUNCTION ActionState_Preassigned()
RETURNS tinyint
AS
BEGIN
RETURN 0
END
GO
CREATE FUNCTION ActionState_Unassigned()
RETURNS tinyint
AS
BEGIN
RETURN 1
END
-- etc...
Where performance matters, still use the hard values.
Probably the best solution for this is a simple look-up table (What is a lookup table?). Nevertheless you can implement something like this:
Solution
SQL Server Management Studio (SSMS)
User.Role is the Foreign Key here, and Role.Type is the Primary Key it refers. And in that table, you'll have the following values:
The type of which must match in both tables. In this case that type is: nvarchar(15)
If you try to add a value at User.Role different than those available at the Role table, you'll get an error.
SQL Code
CREATE TABLE [dbo].[User](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Username] [nvarchar](50) NOT NULL,
[Email] [nvarchar](75) NOT NULL,
[Password] [nvarchar](25) NOT NULL,
[Role] [nvarchar](15) NOT NULL,
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[User] WITH CHECK ADD CONSTRAINT [FK_User_Role] FOREIGN KEY([Role])
REFERENCES [dbo].[Role] ([Type])
GO
ALTER TABLE [dbo].[User] CHECK CONSTRAINT [FK_User_Role]
GO
CREATE TABLE [dbo].[Role](
[Type] [nvarchar](15) NOT NULL,
CONSTRAINT [PK_Role] PRIMARY KEY CLUSTERED
(
[Type] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
Solution 2
You can implement a lookup table like this one: Create enum in SQL Server
You can try something like
ALTER TABLE dbo.yourTable
ADD CONSTRAINT yourColumn CHECK(yourColumn IN('XL','L','M','S','XS'))