日期:2014-05-17  浏览次数:20576 次

t-sql if exists begin end 报错
use master     
go
if exists(select * from sysdatabases where name='ttt')  
begin
print '已经存在'
end
else
begin
    use master
    go
create database ttt
go
use ttt
if exists(select * from sysobjects where name='T_News' and xtype ='U') 
begin
   print '该表已经存在'     
end
else
begin
create table  T_News (
 ID int not null ,
Title varchar(50) not null,
passwd varchar not null
    ) 
end
end


////////
消息 102,级别 15,状态 1,第 7 行
'master' 附近有语法错误。
消息 102,级别 15,状态 1,第 14 行
'end' 附近有语法错误。

------解决方案--------------------
begin 和 end 之间不能用go执行语句
------解决方案--------------------

  if exists(select * from sys.databases where name='ttt') 
    print '数据库已经存在'
  else
    create database ttt
  go
  use ttt
  go
  if exists(select * from sys.objects where name='T_News' and type ='U') 
    print '该表已经存在于ttt数据库'      
  else
    create table T_News(ID int not null,Title varchar(50) not null,passwd varchar not null) 
  go
  

------解决方案--------------------
我个人比较偏向这种,可以运行的,不存在才创建,可以反复运行
use master     
go
IF db_id('ttt')IS  NULL
CREATE DATABASE ttt
go
USE ttt
go
IF OBJECT_ID('T_News','u')IS  NULL
CREATE TABLE T_News
(
 ID int not null ,
Title varchar(50) not null,
passwd varchar not null
    )