从C#,如何在文本框中显示“脚本表作为创建查询”的结果?

时间:2014-02-08 02:00:59

标签: c# sql

我有一个查询

查询:

   declare @vsSQL varchar(8000)
   declare @vsTableName varchar(50)
   select @vsTableName = 'dbo.MyTableName'
   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) + ')'

查询结果:enter image description here

我尝试在listBox1_SelectedIndexChanged中应用此查询,以便在列表框的foreach选定项目的文本框中显示

      private void listBox1_SelectedIndexChanged(object sender, EventArgs e)

    {

      using (SqlConnection con = new SqlConnection(strConnect))

    {

    con.Open();


    using (SqlCommand comQuery = new SqlCommand(@" declare @vsSQL varchar(8000)
    declare @vsTableName varchar(50)
    select @vsTableName = '@SelectedTableFormListBox'
    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("@SelectedTableFormListBox", listBox1.SelectedItem);

   using (SqlDataReader readerQuery = comQuery.ExecuteReader())

    {

   textBox1.Text = "";


   while (readerQuery.Read())

   {

    textBox1.Text = ??

   }


     }  

     }  

     } 

     }

我的问题:我不确定使用选择@vsTableName ='@ SelectedTableFormListBox'

我不知道如何在文本框中显示。

1 个答案:

答案 0 :(得分:0)

我解决了。

更改

    select @vsTableName = '@SelectedTableFormListBox'

    select @vsTableName = @SelectedTableFormListBox

更改

      while (readerQuery.Read())

       {

        textBox1.Text = ??

        }

      while (readerQuery.Read())

       {

        textBox1.Text = readerQuery[0].ToString() ;

       }