Create enum in SQL Server - sql

In MySQL one can create an enum as such:
USE WorldofWarcraft;
CREATE TABLE [users]
(
ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
username varchar(255),
password varchar(255),
mail varchar (255),
rank ENUM ('Fresh meat', 'Intern','Janitor','Lieutenant','Supreme being')DEFAULT 'Fresh meat',
);
This is not possible in SQL Server, so what are the alternatives?
I've read this post
SQL Server equivalent to MySQL enum data type?
Suggesting something like
mycol VARCHAR(10) NOT NULL CHECK (mycol IN('Useful', 'Useless', 'Unknown'))
How can one get that work and create a default value?
The purpose of the enum would be able to tie it to a graphical dropdown on the site which presents the user with values and has a default value pre-specified.

It's better to properly normalize your model:
create table user_rank
(
id integer primary key, -- no identity, so you can control the values
rank varchar(20) not null unique
);
insert into user_rank (id, rank)
values
(1, 'Fresh Meat'),
(2, 'Intern'),
(3, 'Janitor'),
(4, 'Lieutenant'),
(5, 'Supreme being');
CREATE TABLE [users]
(
ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
username varchar(255),
password varchar(255),
mail varchar (255),
rank integer not null default 1,
constraint fk_user_rank foreign key (rank) references user_rank (id)
);
The dropdown on your web site can easily be populated by querying the user_rank table.

There is no enum datatype available in SQL Server like in MySQL.
But using the CHECK constraint enum functionality can be implemented.
USE WorldofWarcraft;
CREATE TABLE [users]
(
ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
username nvarchar(255),
password nvarchar(255),
mail nvarchar (255),
[rank] nvarchar (255) NOT NULL CHECK ([rank] IN('Fresh meat', 'Intern','Janitor','Lieutenant','Supreme being')) DEFAULT 'Fresh meat'
);

Related

How do I insert data into a row in SQL?

I am following a tutorial and learning MVC from a book, where I was told to create a table using this script, which I did. But now I want to add an entire row to my Pet table, but I am unable to do it.
Script used to create all my tables.
CREATE TABLE [dbo].[Setting] (
[Id] INT NOT NULL IDENTITY(1, 1)
,[Key] VARCHAR(50) NOT NULL
,[Value] VARCHAR(500) NULL
,CONSTRAINT [PK_Setting] PRIMARY KEY ([Id])
);
CREATE TABLE [dbo].[PetType] (
[PetTypeID] INT NOT NULL IDENTITY(1, 1)
,[PetTypeDescription] VARCHAR(50) NULL
,CONSTRAINT [PK_PetType] PRIMARY KEY ([PetTypeID])
);
CREATE TABLE [dbo].[Status] (
[StatusID] INT NOT NULL IDENTITY(1, 1)
,[Description] VARCHAR(50) NOT NULL
,CONSTRAINT [PK_Status] PRIMARY KEY ([StatusID])
);
CREATE TABLE [dbo].[Pet] (
[PetID] INT NOT NULL IDENTITY(1, 1)
,[PetName] VARCHAR(100) NOT NULL
,[PetAgeYears] INT NULL
,[PetAgeMonths] INT NULL
,[StatusID] INT NOT NULL
,[LastSeenOn] DATE NULL
,[LastSeenWhere] VARCHAR(500) NULL
,[Notes] VARCHAR(1500) NULL
,[UserId] INT NOT NULL
,CONSTRAINT [PK_Pet] PRIMARY KEY ([PetID])
,CONSTRAINT [FK_Pet_Status] FOREIGN KEY ([StatusID]) REFERENCES [Status]([StatusID])
,CONSTRAINT [FK_Pet_User] FOREIGN KEY ([UserId]) REFERENCES [UserProfile]([UserId])
);
CREATE TABLE [dbo].[PetPhoto] (
[PhotoID] INT NOT NULL IDENTITY(1, 1)
,[PetID] INT NOT NULL
,[Photo] VARCHAR(500) NOT NULL CONSTRAINT [DF_PhotoFile] DEFAULT '/content/pets/no-image.png'
,[Notes] VARCHAR(500) NULL
,CONSTRAINT [PK_PetPhoto] PRIMARY KEY ([PhotoID])
,CONSTRAINT [FK_PetPhoto_Pet] FOREIGN KEY ([PetID]) REFERENCES [Pet]([PetID])
);
CREATE TABLE [dbo].[Message] (
[MessageID] INT NOT NULL
,[UserId] INT NOT NULL
,[MessageDate] DATETIME NOT NULL
,[From] VARCHAR(150) NOT NULL
,[Email] VARCHAR(150) NOT NULL
,[Subject] VARCHAR(150) NULL
,[Message] VARCHAR(1500) NOT NULL
,CONSTRAINT [PK_Message] PRIMARY KEY ([MessageID])
,CONSTRAINT [FK_Message_User] FOREIGN KEY ([UserId]) REFERENCES [UserProfile]([UserId])
);
I want to add some random values(for testing) into my Pet table's first row.
This is the Pet table's first row as an image for further clarity.
I tried using this script to add values to my table.
INSERT INTO Pet VALUES ('1', 'Fido', '12', '4', '1', '12/07/2004', 'New York', 'nothing', '1')
But I got an error saying
An explicit value for the identity column in table 'Pet' can only be specified when a column list is used and IDENTITY_INSERT is ON.
Now I am fairly new to SQL and I am unable to figure this out. I looked at other SO answers where people said something about SET IDENTITY_INSERT, but this didn't work for me as well. I believe I misunderstood other SO answer since I am fairly new to database languages. So need your help.
Thanks
In SQL Server identity is used for autoincrement. identity(1,1) means the starting value for the column will be 1 and will be incremented by 1. You can change it to desired value for example identity(5,2) starts the value at 5 and increments by 2. You no need to specify an explicit value for setting this column, it will be automatically assigned a unique value.
In mysql you can use AUTO_INCREMENT
Refer w3schools page for details sql autoincrement
PetID is defined as IDENTITY so you cannot specify a value to INSERT in that column unless you set "IDENTITY_INSERT" option to ON.
You have two options:
Dont specify that column/value and let SQL generate it for you.
Set IDENTITY_INSERT to ON before your INSERT operation.
Another very cool way to add rows/edit table (including editting deleting rows) is to use Microsoft SQL Management Studio Express. I didn't know about this until I'd been learning SQL for years. Basically expand the tree structure to the left, right-click on a table and choose Edit Table. When you get going with SQL more, you can edit Stored Procedures in here and pretty much anything SQL else you can can think of.
I've blurred out the actual database names but this gives you the gist of it :-

Create table with UNIQUEIDENTIFIER as PK

I have been trying (unsuccessfully) to create a table with a UNIQUEIDENTIFIER as the primary key. The script below will create the table just fine, however there is no PK specified. This is my first time using a UNIQUEIDENTIFIER, however. Any ideas?
T-SQL
CREATE TABLE [dbo].[AgentRelationshipCodes]
(
Id UNIQUEIDENTIFIER NOT NULL DEFAULT NEWID(),
RelationshipId char(3) NULL,
EffectiveDate datetime NULL,
LastChangeDate datetime NOT NULL,
LastChangeId char(6) NOT NULL,
AgtTableId int FOREIGN KEY REFERENCES AgentTransmission(ID)
);
Management Studio
create table [dbo].[AgentRelationshipCodes]
(
Id UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT NEWID(),
.
.
.
)
Repeat for the other tables.
Answered here by Christian Hayter

How i can change and run sql file into mssql

I have my database in sqlite .I exported sql file from sqlite manager. Now on executing that file into Microsoft SQL Server 2012 it is giving error on following lines.
DROP TABLE
IF EXISTS "Admin";
CREATE TABLE "AdvancePayments" (
"Id" INT PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
"date" VARCHAR,
"Name" VARCHAR,
"Amount" INT,
"Remarks" VARCHAR);
INSERT INTO "AdvancePayments"
VALUES (
1,
'11/22/2013',
'wqqw',
21,
'fgdsr');
CREATE TABLE "DVouchers" (
"DVid" INT PRIMARY KEY NOT NULL,
"vdate" VARCHAR DEFAULT(NULL),
"Vehiclenum" VARCHAR,
"Coupen" BOOL,
"Saleperson" VARCHAR,
"DVnumber" INT,
"Ares" VARCHAR,
"Ctitle" VARCHAR,
"remarks" VARCHAR,
"mEntry" BOOL,
"Cust_Id" INT,
FOREIGN KEY (Cust_Id) REFERENCES Customer_New(Cust_Id));
What is correct syntax for mssql?
You should write it as:
--DROP TABLE IF EXISTS Admin;
--query to drop a table
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TableName]') AND type in (N'U'))
DROP TABLE [dbo].[TableName]
GO
CREATE TABLE [AdvancePayments]
(
[Id] INT IDENTITY(1,1) PRIMARY KEY NOT NULL ,--The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature
[date] VARCHAR(10),-- best practice is to use datetime datatype to store date feilds.
[Name] VARCHAR(100),
[Amount] INT,
[Remarks] VARCHAR(1000)
);
INSERT INTO AdvancePayments
VALUES (
--1,-- you cannot give an explicit value to identity column untill IDENTITY_INSERT is ON. So comment this.
'11/22/2013',
'wqqw',
21,
'fgdsr');
CREATE TABLE [DVouchers] (
[DVid] INT PRIMARY KEY NOT NULL,
[vdate] VARCHAR(20) DEFAULT(NULL),
[Vehiclenum] VARCHAR(100),
[Coupen] BIT,-- Bit is the datatype used for Boolean values.
[Saleperson] VARCHAR(100),
[DVnumber] INT,
[Ares] VARCHAR(100),
[Ctitle] VARCHAR(100),
[remarks] VARCHAR(100),
[mEntry] BIT,
[Cust_Id] INT,
FOREIGN KEY (Cust_Id) REFERENCES Customer_New(Cust_Id)
);
Note: In MS SQL default length of varchar datatype is 1. so you will have to specify length to each
varchar variable.
TSQL:
IF NOT OBJECT_ID('dbo.TableToDrop') IS NULL
BEGIN
DROP TABLE dbo.TableToDrop
END;
// change dbo. to your schema if necessary

SQL Server : create error how to write database name with the table name

CREATE DATABASE agom COLLATE Arabic_CI_AS
CREATE TABLE Branches
(
ID INT PRIMARY KEY NOT NULL IDENTITY,
NAME VARCHAR(255) NOT NULL
)
CREATE TABLE agom.Brands
(
ID INT PRIMARY KEY NOT NULL IDENTITY,
NAME VARCHAR(255) NOT NULL
)
CREATE TABLE agom.Work_Order
(
NUMBER INT NOT NULL,
BRANCHID INT NOT NULL,
BRANDID INT NOT NULL,
WDATE DATE NOT NULL,
REPAIRSTATUS VARCHAR(255),
REPAIRCOST VARCHAR(255),
REMARK VARCHAR(500),
PRIMARY KEY (NUMBER,BRANCHID,BRANDID)
)
CREATE TABLE agom.Profiles
(
ID INT PRIMARY KEY NOT NULL IDENTITY,
USERNAME VARCHAR(25) NOT NULL,
PASS VARCHAR(25) NOT NULL
)
ALTER TABLE agom.Work_Order
ADD CONSTRAINT branchfk
FOREIGN KEY (BRANCHID) REFERENCES Branches(ID)
ALTER TABLE agom.Work_Order
ADD CONSTRAINT brandfk
FOREIGN KEY (BRANDID) REFERENCES Brands(ID)
I get an error that cannot create table
I try to write database name with the table name db.tablename but it's not working
I need to create the database then create the tables and its constraints but I don't know where is the error.I am a sql noob
It's never Database.Table.
It's either Table, or Schema.Table, or Database.Schema.Table, or Server.Database.Schema.Table.
You probably just want to insert USE agom right after create database, and then only refer to tables by name.
Alternatively, you can refer to your tables as agom.dbo.Work_Order, dbo being the default database schema.
See Using Identifiers As Object Names for general reference.

Multilingual database design

I'm trying to design a database schema for a multilingual application. I have so far found a sample from this address. http://fczaja.blogspot.com/2010/08/multilanguage-database-design.html
But I haven't understood this sample. Should I insert Id value on app_product first? How can I know that these values are true for ProductId on app_product_translation?
CREATE TABLE ref_language (
Code Char(2)NOT NULL,
Name Varchar(20) NOT NULL,
PRIMARY KEY (Code)
);
CREATE TABLE app_product (
Id Int IDENTITY NOT NULL,
PRIMARY KEY (Id)
);
CREATE TABLE app_product_translation (
ProductId Int NOT NULL,
LanguageCode Char(2) NOT NULL,
Description Text NOT NULL,
FOREIGN KEY (ProductId) REFERENCES app_product(Id),
FOREIGN KEY (LanguageCode) REFERENCES ref_language(Code)
);
It looks like SQLServer code, proceeding on that assumption.
Yes you must insert the app_product first. But you cannot insert the id column's value. It is assigned automatically, because it is an identity column.
Two things you can check out...to find the identity column's value after inserting.
The OUTPUT clause of the INSERT statement. It can return any values that are inserted, not just the identity column.
The ##Identity variable. (by far more traditional and popular)
declare #lastid int
insert into x values (1,2,3)
set #lastid = ##identity
insert into y values (#lastid, a, b, c)