来自存储在表中的值的 SQL 动态 SELECT 语句
我已经研究了几天了,感觉自己在兜圈子。我有 SQL 的基本知识,但有很多地方我不明白。
我有一个表,用于存储数据库中所有其他表的名称和字段。
tblFields
===================================================
TableName FieldName BookmarkName
---------------------------------------------------
Customer FirstName CustomerFirstName
Customer LastName CustomerLastName
Customer DOB CustomerDOB
我想编写一个如下所示的 SELECT 语句,但我无法让它工作:
SELECT (SELECT [FieldName] FROM [TableName]) FROM tblFields
这可能吗?我开发的应用程序需要此功能来进行用户自定义报告。
I have been researching this for a couple of days and feel like I am going around in circles. I have basic knowledge of SQL but there are many areas I do not understand.
I have a table that stores the names and fields of all the other tables in my database.
tblFields
===================================================
TableName FieldName BookmarkName
---------------------------------------------------
Customer FirstName CustomerFirstName
Customer LastName CustomerLastName
Customer DOB CustomerDOB
I want to write a SELECT
statement like the following but i am unable to get it work:
SELECT (SELECT [FieldName] FROM [TableName]) FROM tblFields
Is this possible? The application I have developed requires this for user customization of reports.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我明白你想做什么,我想这会对你有帮助。它并不漂亮,并且适用于 SQL Server 2005 及更高版本,但也许这就是您正在寻找的:
编辑:正如 Martin 建议的那样,我进行了编辑,以便列和表名使用 QUOTENAME
If i understand what you are trying to do, i think this will help you. It is not pretty and it works for SQL Server 2005 and above, but maybe this is what you are looking for:
Edit: As Martin suggested, i edited so that the columns and tablename are using QUOTENAME
如果我正确理解您想要执行的操作,那么您最好将其作为程序中的两个单独的查询来执行。其中一个获取您想要选择的字段,然后在程序中使用该字段来构建实际获取数据的第二个查询。
如果必须完全用 SQL 完成,那么您需要告诉我们您正在使用什么数据库。如果是 SQL Server,您可以在第一个查询上使用游标来构建第二个查询,然后使用 sp_executesql 存储过程执行该查询。但建议在 SQL 之外执行此操作。
If I understand correctly what you are trying to do, you are probably better off doing this as two separate queries from your program. One which gets the fields you want to select which you then use in your program to build up the second query which actually gets the data.
If it must be done entirely in SQL, then you will need to tell us what database you are using. If it is SQL Server, you might be able to user a cursor over the first query to build up the second query which you then execute with the sp_executesql stored procedure. But doing doing it outside of SQL would be recommended.