动态表插入TSQL
大家好,我已经为此苦苦挣扎了一段时间了!我有一些带有日期的数据文件,这些文件被转储到临时表中。我希望我的脚本/函数做的是读取暂存表中每条记录的日期并移动到适当的表。现在我知道我可以很容易地做到这一点,只需使用一些静态插入,例如
INSERT INTO TABLE_2011_08
WHERE Datafields = 2011_08
,但是我希望它是动态的,所以我正在考虑按照函数/存储过程的方式传递每个记录的日期。然而我的大脑有点融化了!
临时表中的数据记录可能是这样的:-
RecordA 2011-08-30 Data Data Data
RecordB 2011-08-31 Data Data Data
RecordC 2011-09-01 Data Data Data
RecordD 2011-09-02 Data Data Data
Hi all i have been struggling this for a while now! I have some data files with a date in them, these are dumped into a staging table. What i would like my script/function to do is to read the date for each record in the staging table and move to the appropriate table. Now i know i could do this very easily just using some static inserts, for example
INSERT INTO TABLE_2011_08
WHERE Datafields = 2011_08
However i want it to be dynamic, so i was thinking something along the lines of a function/stored procedure to pass in the date for each record. However my brain is melting a bit with this!
The data records in the staging table could be something like this:-
RecordA 2011-08-30 Data Data Data
RecordB 2011-08-31 Data Data Data
RecordC 2011-09-01 Data Data Data
RecordD 2011-09-02 Data Data Data
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
开始吧:
现在您的导入过程只需将它们放入表中即可。没有动态要求,也不需要每月创建一个新表。
如果您确实需要使它们看起来独立,那么可以在表上创建视图:
当您有太多行而需要将它们实际放入单独的表中时,这种情况会非常罕见。 (我们谈论的是数十百万行)。现在有了分区,即使那样也可能没有必要了。
将它们放入单独的表中只会使将来使用它们变得更加困难。
Here you go:
Now your import process just has to put them in the table. No dynamic requirements and no need to create a new table every month.
If you really need to make them look separate then create views over the table:
It's going to be pretty rare when you have so many rows that you need to actually put them into separate tables. (we're talking 10's of millions of rows). With partitioning now, even then it probably isn't necessary.
Putting them into separate tables is just going to make it harder to work with them in the future.
如果我理解正确的话,您想生成具有动态更改表名的
INSERT
语句吗?您可以将 SQL 查询构建为字符串并使用 EXEC 执行它:
实现数据路由的最简单方法是使用游标迭代暂存数据并在该循环中创建动态插入 SQL 字符串。
然后使用单个
EXEC
命令执行插入批处理。If i understand you right, you want to generate
INSERT
statements with a dynamically changing table name?You can construct your SQL query as a string and execute it with
EXEC
:The easiest way to achieve your data routing is to iterate your staging data with a cursor and create the dynamic insert sql string in that loop.
Afterwards execute the insert batch with a single
EXEC
command.表 T 与您的表类似,我用与您接近的测试数据填充它,如果您填充的表不存在,则会创建它们。
尝试重新创建表
如果需要,此语法将创建并填充类似 TABLE_YYYY_MM 的表。 YYYY 和 MM 是任意组合,找到它表 T
The table T is similar to your table, I populated it with test data close to yours, the tables you populate will be created if they don't exist.
An attempt to recreate your table
This syntax will if needed create and populate tables like TABLE_YYYY_MM. YYYY and MM is any combination found it table T