常用SQL语句

阅读更多
-------------------------一,数据库操作-----------------------------
------------1,创建数据库------------------
IF DB_ID('TestDB') IS NOT NULL DROP DATABASE TestDB;

CREATE DATABASE TestDB ON
(
    NAME='TestDB',
    FILENAME='d:\mcgrady\db\TestDB.mdf',
    SIZE=4,
    MAXSIZE=10,
    FILEGROWTH=1
);

------------2,备份数据库------------------
BACKUP DATABASE TestDB TO DISK='d:\mcgrady\db\bak\TestDB.bak';

------------4,删除数据库------------------
--IF DB_ID('TestDB') IS NOT NULL DROP DATABASE TestDB;

------------5,删除数据库日志文件------------------
--DBCC ERRORLOG
--GO 6

-------------------------二,数据表操作-----------------------------
USE TestDB;
GO
------------1,创建数据表------------------
IF OBJECT_ID('dbo.SM_User') IS NOT NULL DROP TABLE dbo.SM_User;

CREATE TABLE SM_User
(
    ID INT NOT NULL IDENTITY,
    UserId NVARCHAR(20) NOT NULL,
    PASSWORD NVARCHAR(20) NOT NULL,
    NAME NVARCHAR(20) NOT NULL,
    Gender TINYINT NULL
        CONSTRAINT DFT_User_Gender DEFAULT(0),
    CreateTime DATETIME NULL
        CONSTRAINT DFT_User_CreateTime DEFAULT(GETDATE()),
    DESCRIPTION NVARCHAR(max) NULL,
    CONSTRAINT PK_SM_User PRIMARY KEY(ID)
);

------------2,删除数据表------------------
--IF OBJECT_ID('dbo.SM_User') IS NOT NULL DROP TABLE dbo.SM_User; -- 也可以使用TRUNCATE TABLE

-------------------------三,字段操作-----------------------------
------------1,添加字段------------------
ALTER TABLE dbo.SM_User ADD Item1 NVARCHAR(MAX) NULL;

------------2,修改字段------------------
ALTER TABLE dbo.SM_User ALTER COLUMN Item1 NVARCHAR(50);

------------3,删除字段------------------
ALTER TABLE dbo.SM_User DROP COLUMN Item1;

------------4,添加约束------------------
ALTER TABLE dbo.SM_User ADD CONSTRAINT chk_user_createtime CHECK(CreateTime

你可能感兴趣的:(sql,sql基础)