码迷,mamicode.com
首页 > 数据库 > 详细

SQL-创建表之前判断表是否存在

时间:2018-05-16 13:01:33      阅读:310      评论:0      收藏:0      [点我收藏+]

标签:data   exists   .com   objects   .sql   SQ   com   std   one   

1.SQL脚本
/*
    SQL-创建表之前判断表是否存在
    LDH @ 2018-5-16
*/

USE TestDB
GO

-- 方法 1
IF OBJECT_ID(NBooks, U) IS NOT NULL
BEGIN
    DROP TABLE Books;
END;

-- 方法 2
/*
IF EXISTS (SELECT * FROM sys.objects WHERE name = ‘Books‘)
BEGIN
    DROP TABLE Books;
END;
*/

-- 方法 3
/*
IF EXISTS (SELECT COUNT(1) FROM sys.tables WHERE name = ‘Books‘)
BEGIN
    DROP TABLE Books;
END;
*/

-- Create a new table.
CREATE TABLE Books (
    BookId INT NOT NULL,
    BookName CHAR(50) NOT NULL,
    Price MONEY );

-- Insert data into the table.
INSERT INTO Books(BookId,BookName,Price)VALUES(1001,N人生若只如初见,88);
INSERT INTO Books(BookId,BookName,Price)VALUES(1002,NSQl Server 2017,88);
INSERT INTO Books(BookId,BookName,Price)VALUES(1003,NSQL必知必会,50);
INSERT INTO Books(BookId,BookName,Price)VALUES(1004,N沥川往事,80);
INSERT INTO Books(BookId,BookName,Price)VALUES(1005,N红楼梦,100);
INSERT INTO Books(BookId,BookName,Price)VALUES(1006,N三国演义,100);
INSERT INTO Books(BookId,BookName,Price)VALUES(1007,N西游记,120);
INSERT INTO Books(BookId,BookName,Price)VALUES(1008,N水浒传,100);

-- Select the table you created just now.
SELECT BookId ,
       BookName ,
       Price FROM dbo.Books
2.运行结果

技术分享图片

SQL-创建表之前判断表是否存在

标签:data   exists   .com   objects   .sql   SQ   com   std   one   

原文地址:https://www.cnblogs.com/LifeDecidesHappiness/p/9044793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!