假设您想要n
行和m
列。零表是一个所有值等于零的表。您想要创建维度n
次m
的零表。如何在SQL Server 2014中创建维度为n
和m
的零表?
答案 0 :(得分:3)
动态创建0表:
declare @n int = 10; /* rows */
declare @m int = 10; /* columns */
declare @cols nvarchar(max);
declare @sql nvarchar(max);
select @cols = stuff((
select top (@m) ',' + quotename(n) + ' = 0'
from (
select n=row_number() over (order by (select 1))
from master..spt_values
) t
order by n
for xml path (''), type).value('.','nvarchar(max)')
,1,1,'');
select @sql = '
select ' + @cols + '
from (
select top (@n) n=row_number() over (order by (select 1))
from master..spt_values
) t
';
select @sql as CodeGenerated;
exec sp_executesql @sql, N'@n int', @n;
rextester演示:http://rextester.com/PKLUA61633
返回:
+-----------------------------------------------------------------------------------------+
| CodeGenerated |
+-----------------------------------------------------------------------------------------+
| select [1] = 0,[2] = 0,[3] = 0,[4] = 0,[5] = 0,[6] = 0,[7] = 0,[8] = 0,[9] = 0,[10] = 0 |
| from ( |
| select top (@n) n=row_number() over (order by (select 1)) |
| from master..spt_values |
| ) t |
+-----------------------------------------------------------------------------------------+
并且exec sp_executesql
返回:
+---+---+---+---+---+---+---+---+---+----+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
+---+---+---+---+---+---+---+---+---+----+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+---+----+
答案 1 :(得分:2)
我们可以创建默认值为0的表,如提到的@SQLZim,并使用默认值创建插入脚本。如下
create table #test ([1] int default 0, [2] int default 0)
insert into #test ([1],[2]) default values