您的位置:首页 > 其它

create [table,column],alter column use SMO

2013-04-21 23:49 567 查看
这篇是接着上一篇《add login,create,backup,restore database to Sql Server using SMO》的,主要操作为:

1.Create SQL Server DataBase

2.Create SQL Server Login

3.Create Table,Alter table,Drop Table

顺序不要乱哦,第一步在上一篇我已经操作过了 ,不理解的可以去看哦^_^

由于时间关系,关于Column的的修改 删除,大家可以自己完善下 或者日后我加上;-)

/// <summary>
/// 创建SQLServer登录名 并指派数据库默认权限及数据库用户映射
/// </summary>
private void createLogin()
{
string LoginName = "Ivan";
string LoginPwd = "123abc";
string dbName="DBSMO";
ServerConnection connection = new ServerConnection();
connection.ConnectionString = "Data Source=*.*.*.*;User ID=sa;Password=pwd";
Server server = new Server(connection);//Server srv = new Server("(local)");或者Server srv = new Server();都是默认选择本地数据库服务器
Microsoft.SqlServer.Management.Smo.Login login = server.Logins[LoginName];
if (login != null)
{
login.Drop();
}
login = new Microsoft.SqlServer.Management.Smo.Login(server, LoginName);
login.LoginType = LoginType.SqlLogin;
login.PasswordExpirationEnabled = true;
login.DefaultDatabase = dbName;
login.Create(LoginPwd);
DatabaseMapping dm = new DatabaseMapping(LoginName, dbName, LoginName);//将登录名映射到对应的数据库
//Response.Write("创建SqlServer登录名成功,loginName="+LoginName+"&loginPwd="+LoginPwd);
Database database = server.Databases[dbName];
Microsoft.SqlServer.Management.Smo.User user = database.Users[LoginName];
if (user != null)
{
user.Drop();
}
user = new Microsoft.SqlServer.Management.Smo.User(database, LoginName);
user.Login = LoginName;
user.Create();//创建数据库用户 默认为与之对应的登录名一致
user.AddToRole("db_owner");//给创建的数据库用户 分配数据库角色 db_owner拥有该数据库所有操作权限
}


/// <summary>
/// 创建Table
/// </summary>
private void createTable()
{
string dbName = "DBSMO";
string loginName = "Ivan";
string loginPwd = "123abc";
ServerConnection connection = new ServerConnection();
connection.ConnectionString = "Data Source=*.*.*.*;User ID="+loginName+";Password="+loginPwd+"";
Server server = new Server(connection);
#region 遍历获取当前登录名下所映射的数据库用户所在的数据库对象
foreach(Microsoft.SqlServer.Management.Smo.Login login in server.Logins)
{
if(login.Name==loginName)
{
DatabaseMapping[] dm = login.EnumDatabaseMappings();
foreach(DatabaseMapping dbm in dm)
{
if(dbm.DBName==dbName)
{
string tableName="Ivan1";
Database db = server.Databases[dbName];
Microsoft.SqlServer.Management.Smo.Table table = db.Tables[tableName];
if (table != null)
{
table.Drop();
}
else
{
table = new Microsoft.SqlServer.Management.Smo.Table(db, tableName);
Microsoft.SqlServer.Management.Smo.Column column1 = new Column
{
Name="id",
Parent=table,
DataType=DataType.Int,
Identity=true,
Nullable=false
};

Microsoft.SqlServer.Management.Smo.Column column2 = new Column
{
Name = "name",
Parent = table,
DataType = DataType.NVarChar(200)
};
table.Columns.Add(column1);
table.Columns.Add(column2);
table.Create();//无法创建一个 Column 也不包含的 Table。 每个表必须得包含一个column
Response.Write("表" + tableName + "创建成功");
//另一种写法
Microsoft.SqlServer.Management.Smo.Column column3 = new Column(table, "Date", DataType.DateTime);

table.Columns.Add(column3);
table.Alter();
Response.Write("表"+tableName+"修改成功");
table.Drop();
Response.Write("表" + tableName + "删除成功");
}
}
}
}
}
#endregion
}


2013-04-28:关于创建Table时没有考虑到主键,外键与唯一索引以及默认值的创建 下面贴一段代码示例:

/// <summary>
/// 在DBSmo数据里创建一张表 FileList
/// </summary>
private void createTable()
{
#region
string loginName = "Ivan";
string loginPwd = "123abc";
string dbName = "DBSMO";
ServerConnection connection = new ServerConnection();
connection.ConnectionString = "Data Source=*.*.*.*;User ID="+loginName+";Password="+loginPwd+";";
Server server = new Server(connection);
foreach (Microsoft.SqlServer.Management.Smo.Login login in server.Logins)
{
if (login.Name == loginName)
{
DatabaseMapping[] dm = login.EnumDatabaseMappings();
foreach (DatabaseMapping dbm in dm)
{
if (dbm.DBName == dbName)
{
string tableName = "FileList";
Database db = server.Databases[dbName];
Microsoft.SqlServer.Management.Smo.Table table = db.Tables[tableName];
if (table != null)
{
msg += "数据库中已存在同名表;";
}
else
{
table = new Microsoft.SqlServer.Management.Smo.Table(db, tableName);
Microsoft.SqlServer.Management.Smo.Column column1 = new Column
{
Name = "fileID",
Parent = table,
DataType = DataType.Int,
Identity = true,
Nullable = false
};
Microsoft.SqlServer.Management.Smo.Column column2 = new Column
{
Name = "fileName",
Parent = table,
DataType = DataType.NVarChar(50)
};
Microsoft.SqlServer.Management.Smo.Column column3 = new Column
{
Name = "fileData",
Parent = table,
DataType = DataType.Image
};
Microsoft.SqlServer.Management.Smo.Column column4 = new Column
{
Name = "fileLength",
Parent = table,
DataType = DataType.Int
};
Microsoft.SqlServer.Management.Smo.Column column5 = new Column
{
Name = "mime",
Parent = table,
DataType = DataType.VarChar(50)
};
Microsoft.SqlServer.Management.Smo.Column column6 = new Column
{
Name = "uploadTime",
Parent = table,
DataType = DataType.Date
};

table.Columns.Add(column1);
table.Columns.Add(column2);
table.Columns.Add(column3);
table.Columns.Add(column4);
table.Columns.Add(column5);
table.Columns.Add(column6);
table.Create();
#region 注意这必须是在表创建成功后 因为test_fileUDdefault1 是单独创建的,位于:"可编程性"下面的"默认值"目录下 和table是依赖关系 1:N
Default def = new Default(db, "test_fileUDdefault1");
def.TextHeader = "create default[test_fileUDdefault1] as";
def.TextBody = "getdate()";
def.Create();
def.BindToColumn(table.Name, "uploadTime");

//Bind the default to a column in a table in AdventureWorks2012
//def.BindToColumn("SpecialOffer", "StartDate", "Sales");

//Unbind the default from the column and remove it from the database.
//def.UnbindFromColumn("SpecialOffer", "StartDate", "Sales");
//def.Drop();
#endregion
#region 这是创建主键的 和创建默认值 一样 在表创建成功后执行
// Define Index object on the table by supplying the Table1 as the parent table and the primary key name in the constructor.
Index pk = new Index(table, "test_filePK1");
pk.IndexKeyType = IndexKeyType.DriPrimaryKey;
//add column1 as index column
IndexedColumn idxCol1 = new IndexedColumn(pk, "fileID");
pk.IndexedColumns.Add(idxCol1);
//create the primary key
pk.Create();
#endregion
#region 主键创建后一定包含一个唯一性索引,唯一性索引并不一定就是主键。一个表可以包含多个唯一索引 ∴这是另一个唯一索引关联uploadTime列的
//create unique index on the table
Index unique = new Index(table, "test_fileUnique1");
unique.IndexKeyType = IndexKeyType.DriUniqueKey;
//add column1 as the unique index column
IndexedColumn idxCol2 = new IndexedColumn(unique, "uploadTime");
//create the unique index
unique.Create();
#endregion
msg += "表创建成功!";
#region 表2 然后 创建一个外键 关联表1的主键
Microsoft.SqlServer.Management.Smo.Table table2 = new Microsoft.SqlServer.Management.Smo.Table(db, "Ftable");
Column col21 = new Column(table2, "id", DataType.Int);
Column col22 = new Column(table2, "fid", DataType.Int);
table2.Columns.Add(col21);
table2.Columns.Add(col22);
table2.Create();
// Define a Foreign Key object variable by supplying the Table2 as the parent table and the foreign key name in the constructor.
ForeignKey fk = new ForeignKey(table2, "test_table2FK1");
//add col22 as the foreign key column.
ForeignKeyColumn fkc = new ForeignKeyColumn(fk, "fid", "fileID");
fk.Columns.Add(fkc);
fk.ReferencedTable = "FileList";
fk.Create();
#endregion
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐