SQL 服务器:如何创建具有特定维度 n 和 m 的零 table?

SQL Server: how to create zero table with certain dimensions n and m?

假设您需要 n 行和 m 列。零 table 是所有值都为零的 table。您想要创建维度 nm 的零 table。如何在 SQL Server 2014 中创建尺寸为 nm 的零 table?

动态创建一个 table 的 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

returns:

+-----------------------------------------------------------------------------------------+
|                                      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 returns:

+---+---+---+---+---+---+---+---+---+----+
| 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 |
+---+---+---+---+---+---+---+---+---+----+

我们可以像@SQLZim 提到的那样创建默认值为 0 的表,并使用默认值创建插入脚本。如下

 create table #test ([1] int default 0, [2] int default 0)

 insert into #test ([1],[2]) default values