sql - SQL .How to:从以 data.PIR 开头的表中选择 *
问题描述
想象一下,我有多个 sql 表,它们被命名为:
data.PIR_12
data.PIR_13
data.Pir_2455
data.Pir_somedata
我可以做一些选择吗
select * from data.PIR% where code = 'mycode'
还是因为架构可能不同而不可能?
解决方案
I would second the comments that say "please fix your data structure". Please look up data normalisation & have a long hard think before implementing something like this.
Only when you get to already be huge scale might you need something approaching data buckets..
If you think you need this because you have varying data content, then go back to normalisation and consider abstracting further. You can get as far abstract as (name, value)
Still, if you know the structure and you are sure that dynamic table names are the answer, then in sqlserver you could construct dynamic sql.
declare @sql nvarchar(2000), @sometable nvarchar(50), @myid nvarchar(10)
set @sometable='_12'
set @myid = '12'
set @sql = 'select name from data.pir' + @sometable + ' where value='+@myid
exec @sql
but you are probably into lots of trouble already - these queries are hard to handle the results from or to wrap error handling around.
You can select from the metadata views to get your list of tables. Or put the table list in a table of your own design. And write an iterator to go through the metadata output with your dynamic sql.
there are cases for dynamic sql, but I would suggest long since outmoded (they used to be aimed at dynamic where clauses for complex ad-hoc queries).
In the past I have used these queries for making very large numbers of cross-server callss (the same sp is invoked, only varying the servername (& there are timing reasons to serialise all the calls making loop iteration the most effective approach)
推荐阅读
- http - 如何让 Firefox 缓存大图像?
- shell - 非法选项 -- xargs shell 命令的命令中的 1
- c# - 代码优先更新数据库使用未指定的 localdb 连接字符串
- r - 具有非唯一测试数据的混淆矩阵级别错误
- c# - 无法将 Unity 脚本附加到游戏对象
- python - 在列表的数据框列中用零替换负数
- html - 在引导程序中的行元素内使用边框
- php - PHP cURL - 将数据从 www 发送到本地 IP
- c# - 使用 iText7 库重写简单的 iTextSharp 读取页面功能
- python - 搜索数据帧的一个值,如果它大于参考值,则替换为另一个数据帧中的参考值