SQL Server Create Table With Column Unique Not Null and Not Empty(Check) - sql

How to create a table with a column which is unique, not null and not empty(Check)?
I tried below Query
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName nvarchar(255) NOT NULL,
FirstName nvarchar(255),
Address nvarchar(255),
City nvarchar(255),
CHECK (P_Id>0)
)
When i try to create a table with both UNIQUE and CHECK constraint its throwing following error. Is it possible to use two constraint in a single query?
Major Error 0x80040E14, Minor Error 25501
> CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName nvarchar(255) NOT NULL,
FirstName nvarchar(255),
Address nvarchar(255),
City nvarchar(255),
CHECK (P_Id>0)
)
There was an error parsing the query. [ Token line number = 8,Token line offset = 1,Token in error = CHECK ]. I am using SQL Server 2008.

CREATE TABLE tab
(
id INT,
notnullandnotemptystr VARCHAR(10) NOT NULL UNIQUE CHECK (DATALENGTH(notnullandnotemptystr) > 0)
)

It should be some thing like this.
CREATE TABLE [dbo].[TABLE1](
[COL1] [nvarchar](50) NOT NULL UNIQUE
)
ALTER TABLE [dbo].[TABLE1] WITH CHECK
ADD CONSTRAINT [CK_TABLE1] CHECK (([COL1]<>N''))

for this problem you can use Constraint in sql server
ALTER TABLE TBL WITH CHECK ADD CONSTRAINT [CK_TBL] CHECK
(([dbo].[TBLCheckCustomeUnique](ID)=(1)))
TBLCheckCustomeUnique is a user define function that check this conditions

You can controll the uniqueness of a column or column set by the UNIQUE constraint.
The data stored in the column or column set could be checked/controlled (and forced with various rules) by the CHECK constraint.
The CHECK constraint to achieve your goal is the following:
ALTER TABLE [YourTable]
ADD CONSTRAINT CK_CheckConstraintName
CHECK (LEN([YourColumn]) >= {MinimumColumnWidth})
You can add the constraints in the CREATE TABLE statement or if the table already exists you can add it with the ALTER TABLE .. ADD CONSTRAINT statement.

Related

So I can't have NOT NULL in column definition of temporal tables?

I am using SQL Server 2016 and trying to create Temporal table. Here is the definition:
USE zbachoreTest
GO`enter code here`
IF EXISTS (SELECT 1 FROM sys.tables WHERE name = 'People' AND temporal_type_desc ='SYSTEM_VERSIONED_TEMPORAL_TABLE' )
ALTER TABLE dbo.People SET( SYSTEM_VERSIONING = OFF)
DROP TABLE IF EXISTS dbo.People
CREATE TABLE dbo.People(
PersonID INT IDENTITY(1,1) NOT NULL CONSTRAINT PK_People PRIMARY KEY(PersonID),
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NULL,
StartTime DATETIME2 GENERATED ALWAYS AS ROW START NOT NULL
CONSTRAINT DF_People_StartTime DEFAULT SYSDATETIME(),
EndTime DATETIME2 GENERATED ALWAYS AS ROW END NOT NULL
CONSTRAINT DF_People_EndTime DEFAULT CONVERT(DATETIME2,'9999-12-31 23:59:59.9999999'),
PERIOD FOR SYSTEM_TIME(StartTime,EndTime)
) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.PeopleHistory))
when I run the above code, I am getting the following error message:
Msg 13531, Level 16, State 1, Line 7
Setting SYSTEM_VERSIONING to ON failed because column 'FirstName' does not have the same nullability attribute in tables 'zbachoreTest.dbo.People' and 'zbachoreTest.dbo.PeopleHistory'.
Any smart folks out there please help. Thanks!
Yes, you can.
Do drop table dbo.PeopleHistory first. If it already exists, it will be only validated, not recreated.
From: https://learn.microsoft.com/en-us/sql/relational-databases/tables/creating-a-system-versioned-temporal-table
The history table must always be schema-aligned with the current or
temporal table, in terms of number of columns, column names, ordering
and data types.
and
If the table specified by the HISTORY_TABLE parameter already exists,
it will be validated against the newly created temporal table in terms
of schema consistency and temporal data consistency. If you specify an
invalid history table, the CREATE TABLE statement will fail.

Altering SQL table to add column

I currently have a table with four columns - i wanted to add a fifth column but having some trouble.
I open the table in sql server studio management 2008 and i added the column info like so:
CREATE TABLE [dbo].[Case]
(
CaseId UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
CaseNumber NVARCHAR(50) NOT NULL,
CourtId INT NOT NULL,
DateOpened DATETIME NOT NULL,
)
my addition:
CREATE TABLE [dbo].[Case]
(
CaseId UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
CaseNumber NVARCHAR(50) NOT NULL,
CaseName NVARCHAR(50),
CourtId INT NOT NULL,
DateOpened DATETIME NOT NULL,
)
After adding CaseName column, i tried executing the table in Management Studio but i got the error message "There is already an object named 'Case' in the database."
I tried saving and then building my database hoping that the column will be added but that wasn't successful. I tried a New Query and writing the 'Alter table "case" add CaseName nvarchar(50) but again without luck. It shows that the file is changed with the new column because i saved it but after building my overall database it isn't making any changes. Any helpful tips will be great.
You want to ALTER, as follows:
ALTER TABLE [dbo].[Case] ADD CaseName NVARCHAR(50)
Better yet, you can check for the existance of the column first:
if not exists (SELECT 1 FROM sysobjects INNER JOIN syscolumns ON
sysobjects.id = syscolumns.id
WHERE sysobjects.name = N'Case' AND syscolumns.name = N'CaseName')
ALTER TABLE [dbo].[Case] ADD CaseName NVARCHAR(50)
you should try this
ALTER TABLE [dbo].[Case]
ADD CaseName NVARCHAR(50)
You are trying to create another table Case but one already exists that's why you have an error. When you want to edit a table, you have to use Alter table
Use an Alter table statement instead of Create
If you can't get the Alter statement to work for some reason, you could also drop the existing table and create a new one with the new field, but all your existing rows will be lost.
If you're using SSMS, you can Design the table instead of Edit to add the column.
ALTER is what you need to investigate (F1)
An alternative is.
Create a new table
CREATE TABLE [dbo].[Case2]
(
CaseId UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
CaseNumber NVARCHAR(50) NOT NULL,
CourtId INT NOT NULL,
DateOpened DATETIME NOT NULL,
newcolumn INT NULL
)
Move data from existing table into the new one
INSERT INTO [dbo].[Case2]
SELECT * FROM [dbo].[Case]
Then
DROP TABLE [dbo].[Case]
Then in management studio right-click 'Case2' and re-name it 'Case'
I recommend checking for the existence of the column prior to adding it, especially important when you work with migration scripts.
Here is how I usually do it:
IF NOT EXISTS(SELECT * FROM sys.columns WHERE Name = N'ColumnName' AND Object_ID = Object_ID(N'TableName'))
BEGIN
ALTER TABLE [dbo].TableName ADD ColumnName NVARCHAR(512) null
END

CHECK CONSTRAINT on multiple columns

I use SQL Server 2008
I use a CHECK CONSTRAINT on multiple columns in the same table to try to validate data input.
I receive an error:
Column CHECK constraint for column
'AAAA' references another column,
table 'XXXX'.
CHECK CONSTRAINT does not work in this way.
Any other way to implement this on a single table without using FK?
Thanks
Here an example of my code
CREATE TABLE dbo.Test
(
EffectiveStartDate dateTime2(2) NOT NULL,
EffectiveEndDate dateTime2(2) NOT NULL
CONSTRAINT CK_CmsSponsoredContents_EffectiveEndDate CHECK (EffectiveEndDate > EffectiveStartDate),
);
Yes, define the CHECK CONSTRAINT at the table level
CREATE TABLE foo (
bar int NOT NULL,
fred varchar(50) NOT NULL,
CONSTRAINT CK_foo_stuff CHECK (bar = 1 AND fred ='fish')
)
You are declaring it inline as a column constraint
...
fred varchar(50) NOT NULL CONSTRAINT CK_foo_fred CHECK (...)
...
Edit, easier to post than describe. Fixed your commas.
CREATE TABLE dbo.Test
(
EffectiveStartDate dateTime2(2) NOT NULL,
EffectiveEndDate dateTime2(2) NOT NULL, --need comma
CONSTRAINT CK_CmsSponsoredContents_EffectiveEndDate CHECK (EffectiveEndDate > EffectiveStartDate) --no comma
);
Of course, the question remains are you using a CHECK constraint where it should be an FK constraint...?
Check constraints can refer to a single column or to the whole record.
Use this syntax for record-level constraints:
ALTER TABLE MyTable
ADD CONSTRAINT MyCheck
CHECK (...your check expression...)
You can simply apply your validation in a trigger on the table especially that either way the operation will be rolled back if the check failed.
I found it more useful for CONSTRAINT using case statements.
ALTER TABLE dbo.ProductStock
ADD
CONSTRAINT CHK_Cost_Sales
CHECK ( CASE WHEN (IS_NOT_FOR_SALE=0 and SAL_CPU <= SAL_PRICE) THEN 1
WHEN (IS_NOT_FOR_SALE=1 ) THEN 1 ELSE 0 END =1 )

Alter a MySQL column to be AUTO_INCREMENT

I’m trying to modify a table to make its primary key column AUTO_INCREMENT after the fact. I have tried the following SQL, but got a syntax error notification.
ALTER TABLE document
ALTER COLUMN document_id AUTO_INCREMENT
Am I doing something wrong or is this not possible?
+--------------------+
| VERSION() |
+--------------------+
| 5.0.75-0ubuntu10.2 |
+--------------------+
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment
Roman is right, but note that the auto_increment column must be part of the PRIMARY KEY or a UNIQUE KEY (and in almost 100% of the cases, it should be the only column that makes up the PRIMARY KEY):
ALTER TABLE document MODIFY document_id INT AUTO_INCREMENT PRIMARY KEY
In my case it only worked when I put not null. I think this is a constraint.
ALTER TABLE document MODIFY COLUMN document_id INT NOT NULL AUTO_INCREMENT;
You can apply the atuto_increment constraint to the data column by the following query:
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
But, if the columns are part of a foreign key constraint you, will most probably receive an error. Therefore, it is advised to turn off foreign_key_checks by using the following query:
SET foreign_key_checks = 0;
Therefore, use the following query instead:
SET foreign_key_checks = 0;
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
SET foreign_key_checks = 1;
The SQL to do this would be:
ALTER TABLE `document` MODIFY COLUMN `document_id` INT AUTO_INCREMENT;
There are a couple of reasons that your SQL might not work. First, you must re-specify the data type (INT in this case). Also, the column you are trying to alter must be indexed (it does not have to be the primary key, but usually that is what you would want). Furthermore, there can only be one AUTO_INCREMENT column for each table. So, you may wish to run the following SQL (if your column is not indexed):
ALTER TABLE `document` MODIFY `document_id` INT AUTO_INCREMENT PRIMARY KEY;
You can find more information in the MySQL documentation: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html for the modify column syntax and http://dev.mysql.com/doc/refman/5.1/en/create-table.html for more information about specifying columns.
You must specify the type of the column before the auto_increment directive, i.e. ALTER TABLE document MODIFY COLUMN document_id INT AUTO_INCREMENT.
AUTO_INCREMENT is part of the column's datatype, you have to define the complete datatype for the column again:
ALTER TABLE document
ALTER COLUMN document_id int AUTO_INCREMENT
(int taken as an example, you should set it to the type the column had before)
You can do it like this:
alter table [table_name] modify column [column_name] [column_type] AUTO_INCREMENT;
You can use the following query to make document_id to increment automatically
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment
It is preferred to make document_id primary key as well
ALTER TABLE document MODIFY COLUMN document_id INT auto_increment PRIMARY KEY;
Below statement works. Note that you need to mention the data type again for the column name (redeclare the data type the column was before).
ALTER TABLE document
MODIFY COLUMN document_id int AUTO_INCREMENT;
AUTO_INCREMENT is part of the column's datatype, you have to define the complete datatype for the column again:
ALTER TABLE document
MODIFY COLUMN document_id int AUTO_INCREMENT
(int taken as an example, you should set it to the type the column had before)
If none of the above works try this. This is what I did in MYSQL and yes, you need to write the column name (document_id) twice.
ALTER TABLE document
CHANGE COLUMN document_id document_id INT(11) NOT NULL AUTO_INCREMENT ;
Setting column as primary key and auto_increment at the same time:
mysql> ALTER TABLE persons MODIFY COLUMN personID INT auto_increment PRIMARY KEY;
Query OK, 10 rows affected (0.77 sec)
Records: 10 Duplicates: 0 Warnings: 0
mysql>
To modify the column in mysql we use alter and modify keywords. Suppose we have created a table like:
create table emp(
id varchar(20),
ename varchar(20),
salary float
);
Now we want to modify type of the column id to integer with auto increment. You could do this with a command like:
alter table emp modify column id int(10) auto_increment;
Previous Table syntax:
CREATE TABLE apim_log_request (TransactionId varchar(50) DEFAULT NULL);
For changing the TransactionId to auto increment use this query
ALTER TABLE apim_log_request MODIFY COLUMN TransactionId INT auto_increment;
alter table tbl_user MODIFY COLUMN id int(10) auto_increment;
Just like this:
alter table document modify column id int(11) auto_increment;
As you are redefining the column again, you have to specify the datatype again and add auto_increment to it as it's a part of datatype.
ALTER TABLE `document` MODIFY COLUMN `document_id` INT AUTO_INCREMENT;
Try the following:
ALTER TABLE table_name MODIFY COLUMN id datatype auto_increment;
Since SQL tag is attached to the question I really think all answers missed one major point.
MODIFY command does not exist in SQL server So you will be getting an error when you run the
ALTER TABLE Satellites MODIFY COLUMN SatelliteID INT auto_increment PRIMARY KEY;
In this case you can either add new column as INT IDENTITY
ALTER TABLE Satellites
ADD ID INT IDENTITY
CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED;
OR
Fill the existing null index with incremental numbers using this method,
DECLARE #id INT
SET #id = 0
UPDATE Satellites SET #id = SatelliteID = #id + 1
Use the following queries:
ALTER TABLE YourTable DROP COLUMN IDCol
ALTER TABLE YourTable ADD IDCol INT IDENTITY(1,1)

In SQL Server 2005, how do I set a column of integers to ensure values are greater than 0?

This is probably a simple answer but I can't find it. I have a table with a column of integers and I want to ensure that when a row is inserted that the value in this column is greater than zero. I could do this on the code side but thought it would be best to enforce it on the table.
Thanks!
I was in error with my last comment all is good now.
You can use a check constraint on the column. IIRC the syntax for this looks like:
create table foo (
[...]
,Foobar int not null check (Foobar > 0)
[...]
)
As the poster below says (thanks Constantin), you should create the check constraint outside the table definition and give it a meaningful name so it is obvious which column it applies to.
alter table foo
add constraint Foobar_NonNegative
check (Foobar > 0)
You can get out the text of check constraints from the system data dictionary in sys.check_constraints:
select name
,description
from sys.check_constraints
where name = 'Foobar_NonNegative'
Create a database constraint:
ALTER TABLE Table1 ADD CONSTRAINT Constraint1 CHECK (YourCol > 0)
You can have pretty sophisticated constraints, too, involving multiple columns. For example:
ALTER TABLE Table1 ADD CONSTRAINT Constraint2 CHECK (StartDate<EndDate OR EndDate IS NULL)
I believe you want to add a CONSTRAINT to the table field:
ALTER TABLE tableName WITH NOCHECK
ADD CONSTRAINT constraintName CHECK (columnName > 0)
That optional NOCHECK is used to keep the constraint from being applied to existing rows of data (which could contain invalid data) & to allow the constraint to be added.
Add a CHECK constraint when creating your table
CREATE TABLE Test(
[ID] [int] NOT NULL,
[MyCol] [int] NOT NULL CHECK (MyCol > 1)
)
you can alter your table and add new constraint like bellow.
BEGIN TRANSACTION
GO
ALTER TABLE dbo.table1 ADD CONSTRAINT
CK_table1_field1 CHECK (field1>0)
GO
ALTER TABLE dbo.table1 SET (LOCK_ESCALATION = TABLE)
GO
COMMIT