日期:2014-05-20  浏览次数:20925 次

怎样用程序或者SQL语句实现表结构的生成?包括主键,外键关联以及约束等关系也要生成
怎样用程序或者SQL语句实现表结构的生成?包括主键,外键关联以及约束等关系也要生成

------解决方案--------------------
ADOX 控件(动态生成access)
------解决方案--------------------
string _sqlstrr = "select * from PsnInfo ";
this._mDa = new SqlDataAdapter(_sqlstrr,this._mConn);
this._mDa.Fill(this._mDs, "PersonInfo ");

DataSet ds = new DataSet();
ds = this._mDs.Clone();//_mDs为当前数据源
------解决方案--------------------
CREATE PROCEDURE GetTableInfo
@TableName varchar(50)
AS
SELECT
(case when a.colorder=1 then d.name else ' ' end) N 'TableName ',
a.colorder N '字段序号 ',
a.name N 'ColName ',
(case when COLUMNPROPERTY( a.id,a.name, 'IsIdentity ')=1 then '√ 'else ' ' end) N 'Identity ',
(case when (SELECT count(*)
FROM sysobjects
WHERE (name in
(SELECT name
FROM sysindexes
WHERE (id = a.id) AND (indid in
(SELECT indid
FROM sysindexkeys
WHERE (id = a.id) AND (colid in
(SELECT colid
FROM syscolumns
WHERE (id = a.id) AND (name = a.name))))))) AND
(xtype = 'PK '))> 0 then '√ ' else ' ' end) N 'PrimaryKey ',
b.name N 'DataType ',
a.length N '占用字节数 ',
COLUMNPROPERTY(a.id,a.name, 'PRECISION ') as N 'Length ',
isnull(COLUMNPROPERTY(a.id,a.name, 'Scale '),0) as N 'Scale ',
(case when a.isnullable=1 then '√ 'else ' ' end) N 'KongZhi ',
isnull(e.text, ' ') N 'Default ',
isnull(g.[value], ' ') AS N 'Description '
FROM syscolumns a left join systypes b
on a.xtype=b.xusertype
inner join sysobjects d
on a.id=d.id and d.xtype in ( 'U ', 'V ') and d.name <> 'dtproperties ' and d.name=@TableName
left join syscomments e
on a.cdefault=e.id
left join sysproperties g
on a.id=g.id AND a.colid = g.smallid
order by object_name(a.id),a.colorder

GO
------解决方案--------------------
存储过程最好,记住在生成前去检测表是否存在
------解决方案--------------------
up
可以自己写存储过程如ls,
或者干脆用数据库生成sql脚本即可
------解决方案--------------------
if exists (select * from dbo.sysobjects where id = object_id(N '[dbo].[PsnInfo] ') and OBJECTPROPERTY(id, N 'IsUserTable ') = 1)
drop table [dbo].[PsnInfo]
GO

if exists (select * from dbo.sysobjects where id = object_id(N '[dbo].[PsnDetail] ') and OBJECTPROPERTY(id, N 'IsUserTable ') = 1)
drop table [dbo].[PsnDetail]
GO

CREATE TABLE [dbo].[PsnInfo] (
[PersonID] [int] NOT NULL ,
[PersonName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[PersonAddress] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[PSex] [bit] NULL ,
[PAge] [int] NULL ,
[Preal] [real] NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[PsnDetail] (
[PersonID] [int] NULL ,
[aa] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[bb] [nchar] (10) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[PsnInfo] WITH NOCHECK ADD
CONSTRAINT [PK_PerInfo] PRIMARY KEY CLUSTERED