Sql 函数根据不同表的条件从多个表中选择行
有人能帮我回答这个问题吗 我正在使用SQLServer2008。目标是根据不同表中的条件和值从多个表中选择行Sql 函数根据不同表的条件从多个表中选择行,sql,sql-server,sql-server-2008,tsql,sql-function,Sql,Sql Server,Sql Server 2008,Tsql,Sql Function,有人能帮我回答这个问题吗 我正在使用SQLServer2008。目标是根据不同表中的条件和值从多个表中选择行 我有table1、table2、tableN,其中列为ID、ColumnName、ColumnValue。这些是我需要根据下表中的条件选择行的表 列号、功能和启用的控制表 具有列函数和表名的存储库表 我需要passnumber和ID作为参数,从Enable value=1的控制表中获取所有函数值的详细信息,并使用这些函数值从存储库表中收集表名。对于从存储库表返回的每个tableName,
我需要passnumber和ID作为参数,从Enable value=1的控制表中获取所有函数值的详细信息,并使用这些函数值从存储库表中收集表名。对于从存储库表返回的每个tableName,使用ID值获取所有行。据我所知,您有两个具有如下模式的表:
table Control (Number int, Function nvarchar, Enable bit)
table Repository (Function nvarchar, TableName nvarchar)
控件
和存储库
通过函数
列进行关联
您还有许多其他表,这些表的名称保存在存储库表中。所有这些表都有ID
列
您希望根据一个数字获取这些表名,然后按ID列从所有这些表中进行选择
如果这确实是您想要做的,下面的代码应该足以解决您的问题
declare
-- arguments
@id int = 123,
@number int = 123456,
-- helper variables we'll use along the way
@function nvarchar(4000),
@tableName nvarchar(256),
@query nvarchar(4000)
-- create cursor to iterate over every returned row one by one
declare cursor #tables readonly fast_forward
for
select
c.Function,
r.TableName
from [Control] as c
join [Repository] as r on r.Function = c.Function
where c.Number = @number
and c.Enable = 1
-- initialise cursor
open #tables
-- get first row into variables
fetch next from #tables
into @function, @tableName
-- will be 0 as long as fetch next returns new values
while @@fetch_status = 0
begin
-- build a dynamic query
set @query = 'select * from ' + @tableName + ' where ID = ' + @id
-- execute dynamic query. you might get permission problems
-- dynamic queries are best to avoid, but I don't think there's another solution for this
exec(@query)
-- get next row
fetch next from #tables
into @function, @tableName
end
-- destroy cursor
close #tables
deallocate #tables
如果没有看到您的模式,就很难理解您的模式和需求。你能分享这些表格中的一些样本数据和你想要的结果吗?“有人能帮我查询吗?”我看不到任何查询!!!学习如何提问。那也许有人会帮忙。请阅读一些关于改进问题的提示。谢谢你的帮助,博士,我将提高我的提问技巧!