2016-03-06 58 views
0

我有这样的代码:SqlCommand的选择命令别名

SqlConnection Connection = new SqlConnection("data source=.;initial catalog=testdb;integrated security=sspi"); 
SqlCommand Command = new SqlCommand("select * from (select count(studentid) from student) as student", Connection); 

Connection.Open(); 
Command.ExecuteNonQuery(); 

我希望查询来自用户,所以我需要后,选择过滤它是写我的方式:

select * from (user query) as table 

但它会抛出一个错误:

No column name was specified for column 1 of 'student'.

因为某些时候列必须别名,如果它是一个函数像count或a vg

我需要用这种方式在用户编写之后过滤查询。此外,我知道分组后将不能工作,并必须在SQL查询中有一个聚合方法...

任何想法?

回答

0

这应该可能是一个评论,但我认为这里的格式更清晰。

逻辑上有

SELECT * 
FROM ({query}) AS STUDENT 

{query} 

所以没有什么区别什么是你真正想干什么?

+0

有时用户输入的SQL查询有一个列需要通过studentlevel 被混叠从学生组 userquery =选择studentlevel,计数(studentid)这是一个预期的输入 我需要过滤这个查询 使用哪里不工作,因为我需要分组后过滤器 ,所以我需要把它以这种方式 select * from(select select studentlevel,count(studentid)from student group by studentlevel) where column = value 使用where之后由 这就是我想要做的 –

+0

@MustafaMuawiaIbrahim - 好的...但你写的代码并不能帮助 - 那是你在问什么 - 如何解决用户输入不好的问题? – Hogan

+0

这不是一个坏的用户输入...... 它的预期的用户输入...... 我需要使用户不要强迫他别名列 –

0

你只是缺少别名为学生

select * from (select count(studentid) as CountOfStudents from student) as student 
0

你无论是在代码和SQL语法犯了一些错误的计数。你收到的错误是因为你有一个混淆的查询,询问了没有给它名字的学生的数量,那么你选择这个单一的值,并尝试给一个表的名字...此外,你使用ExecuteNonQuery的名称告诉它在SQL服务器上执行一些SQL,并且不会检索任何内容,这种命令通常用于执行用于插入或更新数据的语句。正确的代码,如下所示:

SqlConnection Connection = new SqlConnection("data source=.;initial 
catalog=testdb;integrated security=sspi;persist security info=true"); 
SqlCommand Command = new SqlCommand("select count(studentid) AS StudentsNumber from student", Connection); 

Connection.Open(); 
object result = Command.ExecuteScalar(); 
MessageBox.Show(result.ToString()); 
+0

我只是测试查询....我将使用读者.....但这个想法是:..... \t \t 有时用户输入一个sql查询有一列需要被别名userquery = select studentlevel,count(studentid)from student group by studentlevel ....这是一个预期的输入我需要过滤这个查询,使用where因为分组不工作,所以我需要在过滤器之后进行分组,因此我需要以这种方式进行分组select * from(select从studentlevel选择studentlevel,从学生组计数(studentid))where column = value使用where经过分组后,这就是我想要做的 –

+0

如果你想分组过滤后你不能使用计数功能,因为计数功能是一个分组功能。此外,如果您希望为用户提供过滤数据的可能性,则不能只获取学生ID的数量,但需要获取希望用户能够过滤数据的字段的全部内容,然后数你想要的并得到它。 –