读书人

@top 附近有语法异常

发布时间: 2012-09-03 09:48:39 作者: rapoo

'@top' 附近有语法错误。
SqlParameter 无法对sql语句中的单个参数赋值吗?

下面是sql:


create table [testInfo]

(

id int identity(1,1) not null,

[name] varchar(50) not null

)

go


insert into [testInfo] values('aaa')

insert into [testInfo] values('bbb')

insert into [testInfo] values('ccc')


下面是程序代码:

SqlConnection conn = new SqlConnection("server=.;database=testDb;uid=sa;pwd=sasa");

conn.Open();

SqlCommand cmd = new SqlCommand("select top @top id from [testInfo]", conn);

cmd.CommandType = System.Data.CommandType.Text;

cmd.Parameters.Add(new SqlParameter(){ParameterName="@top", Value=1,DbType=System.Data.DbType.Int32});

SqlDataReader sdr= cmd.ExecuteReader();

sdr.Read();

this.ClientScript.RegisterStartupScript(this.GetType(),"","alert('"+sdr["id"]+"')",true);

conn.Close();

界面上就一个按钮:

<asp:Button runat="server" ID="btn"

onclick="btn_Click1" />

错误提示是: '@top' 附近有语法错误。


如果把程序代码改成这样就没问题:

SqlConnection conn = new SqlConnection("server=.;database=testDb;uid=sa;pwd=sasa");

conn.Open();

SqlCommand cmd = new SqlCommand("select id from [testInfo] where id=@top", conn);

cmd.CommandType = System.Data.CommandType.Text;

cmd.Parameters.Add(new SqlParameter(){ParameterName="@top", Value=1,DbType=System.Data.DbType.Int32});

SqlDataReader sdr= cmd.ExecuteReader();

sdr.Read();

this.ClientScript.RegisterStartupScript(this.GetType(),"","alert('"+sdr["id"]+"')",true);

conn.Close();


这样证明top这个sql关键字后的@top无法赋值,为什么会这样?


[解决办法]
可以用变量,要加括号 select top (@top)

读书人网 >asp.net

热点推荐