SQL Server 2008:复杂插入
我有一个名为 Employees
的表:
BeginYear | EndYear | Name
1974 1983 Robert
对于 Employees
中的每条记录,我需要将每年插入到名为 EmployeeYears
的新表中,
因此:
For Each Record in Employees
For i as int = Begin Year to End year
INSERT i, Name into EmployeeYears
有什么方法可以在 SQL 中执行此操作...可能使用游标吗?
I have a table called Employees
:
BeginYear | EndYear | Name
1974 1983 Robert
For each record in Employees
I need to insert each year into a new table called EmployeeYears
So:
For Each Record in Employees
For i as int = Begin Year to End year
INSERT i, Name into EmployeeYears
Any Way to do this in SQL...possibly with cursors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
它的要点是使用WITH语句创建所有记录并使用它们插入到最终表中。
测试数据
结果
The gist of it is using a WITH statement to create all the records and use them to insert into your final table.
Testdata
Results
如果您有一个数字表,您可以加入它以获取各个年份的记录并避免使用游标。我只是用 1965 到 968 之间的数字填充数字表,但是现实生活中的数字表(出于示例目的,它也不会是如下所示的临时表,而是存在于您的模式中的表)可能有几百万条记录,因为它对于很多比较很有用。
If you have a numbers table you can join on it to get the individual year records and avoid using a cursor. I just poulated the numbers table with number from 1965 to 968, but a realife numbers table (which also would not be a temp table as shown below for example purposes, but one that lives in your schema) would probably have several million records as it is useful for a lot of comparing.
是的,你实际上必须做一个循环...我不想使用游标,但这种情况有点有意义...无论如何,这里的代码只是一个直接循环,向您展示您可以执行这种代码在 SQL 中:
Yes, you actually have to do a loop... I'd prefer not using CURSORS, but this case sorta makes sense... anyway, here's the code as just a straight loop to show you that you can do that kind of code in SQL:
您可以使用递归 CTE:
You can use a recursive CTE:
您可以使用递归过程。就像下面这个:
You can use a recursive procedure. Llike the one bellow:
你可以这样做,但如果 Begin 或 end 超过 2047,它将失败
You could do this but it will fail if Begin or end exceeds 2047