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


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

USE TestDB
GO

-- 方法 1
IF OBJECT_ID(N'Books', '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',N'SQl Server 2017','88');
INSERT INTO Books(BookId,BookName,Price)VALUES('1003',N'SQL必知必会','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.运行结果


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM