asp.net產生新資料表

2010-03-17 9:27 am
操作環境:VWD2008,MS SQL SERVER 2008
語言:C#
我想利用輸入的字串,以輸入字串為名的新表單如何做

protected void Button1_Click(object sender, EventArgs e)
{
String x=TextBox1.text;//將輸入字串變成字串變數
SqlConnection Conn = new SqlConnection("game");
Conn.Open();

} //以連接好資料庫

SQL語法
CREATE TABLE [dbo].[輸入字串為名](
[id] [int] IDENTITY(1,1) NOT NULL,
[背號] [int] NULL,
[姓名] [nchar](10) NULL,
[位置] [nchar](10) NULL,
[先發] [int] NULL,
[三分球試投] [int] NULL,
[三分球試投(中)] [int] NULL,
[兩分球試投] [int] NULL,
[兩分球試投(中)] [int] NULL,
)

如何在C#中達到我的SQL語法要求??
更新1:

我想利用輸入的字串,以輸入字串為名產生新表單如何做??

回答 (1)

2010-03-17 2:18 pm
✔ 最佳答案
方法一
protected void Button1_Click(object sender, EventArgs e)
{
string x = TextBox1.Text;//將輸入字串變成字串變數
SqlConnection Conn = new SqlConnection(connection_string);
Conn.Open();

SqlCommand cmd = Conn.CreateCommand();
string sql = "CREATE TABLE [dbo].[" + x + "] (" +
"[id] [int] IDENTITY(1,1) NOT NULL," +
"[背號] [int] NULL," +
"[姓名] [nchar](10) NULL," +
"[位置] [nchar](10) NULL," +
"[先發] [int] NULL," +
"[三分球試投] [int] NULL," +
"[三分球試投(中)] [int] NULL," +
"[兩分球試投] [int] NULL," +
"[兩分球試投(中)] [int] NULL )";
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}

方法二
先在 SQL Server 裏建立一個表單的模板,TempTable

protected void Button1_Click(object sender, EventArgs e)

{

string x = TextBox1.Text;//將輸入字串變成字串變數

SqlConnection Conn = new SqlConnection(connection_string);

Conn.Open();



SqlCommand cmd = Conn.CreateCommand();
string sql = "select * into " + x + " from TempTable";
cmd.CommandText = sql;

cmd.ExecuteNonQuery();

}

方法二新表單會建立 identity 欄,但不會設預設值 (default value),設預設值加以下程式

sql = "ALTER TABLE " + x + " ADD " +
"CONSTRAINT [DF_" + x + "_三分球試投] DEFAULT (0) FOR [三分球試投]";
cmd.CommandText = sql;


cmd.ExecuteNonQuery();


收錄日期: 2021-04-25 20:34:53
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20100317000010KK00702

檢視 Wayback Machine 備份