SqlConnection con = new SqlConnection("server=150.0.1.200;user=sa;password=sa;database=test");
string sql = "Create Table testtable(test1 varchar not null primary key,test2 int)";
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex){MessageBox.Show(ex.Message);}
finally
{
cmd.Connection.Close();
}最好适用存储过程来做,在程序里写,语句在串接的时候很容易出错。
string sql = "Create Table testtable(test1 varchar not null primary key,test2 int)";
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex){MessageBox.Show(ex.Message);}
finally
{
cmd.Connection.Close();
}最好适用存储过程来做,在程序里写,语句在串接的时候很容易出错。
Creates a new table.Syntax
CREATE TABLE
[ database_name.[ owner ] . | owner. ] table_name
( { < column_definition >
| column_name AS computed_column_expression
| < table_constraint > ::= [ CONSTRAINT constraint_name ] } | [ { PRIMARY KEY | UNIQUE } [ ,...n ]
) F. Complete table definitions
This example shows complete table definitions with all constraint definitions for three tables (jobs, employee, and publishers) created in the pubs database.举例/* ************************** jobs table ************************** */
CREATE TABLE jobs
(
job_id smallint
IDENTITY(1,1)
PRIMARY KEY CLUSTERED,
job_desc varchar(50) NOT NULL
DEFAULT 'New Position - title not formalized yet',
min_lvl tinyint NOT NULL
CHECK (min_lvl >= 10),
max_lvl tinyint NOT NULL
CHECK (max_lvl <= 250)
)/* ************************* employee table ************************* */
CREATE TABLE employee
(
emp_id empid
CONSTRAINT PK_emp_id PRIMARY KEY NONCLUSTERED
CONSTRAINT CK_emp_id CHECK (emp_id LIKE
'[A-Z][A-Z][A-Z][1-9][0-9][0-9][0-9][0-9][FM]' or
emp_id LIKE '[A-Z]-[A-Z][1-9][0-9][0-9][0-9][0-9][FM]'),
/* Each employee ID consists of three characters that
represent the employee's initials, followed by a five
digit number ranging from 10000 through 99999 and then the
employee's gender (M or F). A (hyphen) - is acceptable
for the middle initial. */
fname varchar(20) NOT NULL,
minit char(1) NULL,
lname varchar(30) NOT NULL,
job_id smallint NOT NULL
DEFAULT 1
/* Entry job_id for new hires. */
REFERENCES jobs(job_id),
job_lvl tinyint
DEFAULT 10,
/* Entry job_lvl for new hires. */
pub_id char(4) NOT NULL
DEFAULT ('9952')
REFERENCES publishers(pub_id),
/* By default, the Parent Company Publisher is the company
to whom each employee reports. */
hire_date datetime NOT NULL
DEFAULT (getdate())
/* By default, the current system date is entered. */
)参照一楼,当个SqlCommand运行,如果是其他用户,要设定建表的权限