如何在文本框中显示具有数据类型长度的“脚本表作为创建查询”的结果?

时间:2014-02-11 13:56:28

标签: c# sql

我可以在列表框中显示所选表名的“脚本表作为查询创建”的结果。

Listbox的SelectedIndexChanged:

     private void ListBoxTableNames_SelectedIndexChanged(object sender, EventArgs e)

      {
        string table = ListBoxTableNames.SelectedItem.ToString();


        using (SqlConnection con = new SqlConnection(strConnectDB1))
        {
            con.Open();


            using (SqlCommand comQuery = new SqlCommand(@"declare @vsSQL varchar(8000)
                declare @vsTableName varchar(50)
                select @vsTableName = @TT
                select @vsSQL = 'CREATE TABLE ' + @vsTableName + char(10) + '(' + char(10)
                select @vsSQL = @vsSQL + ' ' + sc.Name + ' ' +
                st.Name +
                case when st.Name in ('varchar','varchar','char','nchar') then '(' + 
                cast(sc.Length as varchar) + ') ' else ' ' end +
                case when sc.IsNullable = 1 then 'NULL' else 'NOT NULL' end + ',' + char(10)
                from sysobjects so
                join syscolumns sc on sc.id = so.id
                join systypes st on st.xusertype = sc.xusertype
                where so.name = @vsTableName
                order by
                sc.ColID
                select substring(@vsSQL,1,len(@vsSQL) - 2) + char(10) + ')'", con))
            {

                comQuery.Parameters.AddWithValue("@TT", ListBoxTableNames.SelectedItem);


                using (SqlDataReader readerQuery = comQuery.ExecuteReader())
                {

                   QueryOfSelectedTableName.Text="";

                    while (readerQuery.Read())
                    {
                        QueryOfSelectedTableName.Text = readerQuery[0].ToString();


                    }

                }


            }
        }

    }

此代码的结果:

  QueryOfSelectedTableName.Text = CREATE TABLE TableName (Id int NOT NULL,  Name nvarchar NOT NULL,  SurName nvarchar NOT NULL,  Adress nvarchar NOT NULL )

但是我需要这样的数据类型长度:

 QueryOfSelectedTableName.Text= CREATE TABLE TableName (Id int NOT NULL,  Name nvarchar(50) NOT NULL,  SurName nvarchar(50) NOT NULL,  Adress nvarchar(50) NOT NULL )

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您的列表中缺少 nvarchar

您的代码:

case when st.Name in ('varchar','varchar','char','nchar')