有人可以帮忙解决这个问题吗?
我正在使用SQL Server 2008。目标是根据不同表中的条件和值从多个表中选择行。
我需要传递Number和ID作为参数,并从Control表中获取Enable value = 1的所有Function值的详细信息,并使用这些函数值从Repository表中收集tableNames。对于从Repository表返回的每个tableName,使用ID值获取所有行。
答案 0 :(得分:1)
我理解它的方式你有两个带有这样的模式的表:
table Control (Number int, Function nvarchar, Enable bit)
table Repository (Function nvarchar, TableName nvarchar)
Control
和Repositories
通过Function
列相关联。
您还有许多其他表,这些表的名称保存在存储库表中。所有这些表都有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