SQL Server:如何创建具有特定维度n和m的零表?

时间:2017-04-29 11:03:45

标签: sql sql-server sql-server-2014 sparse-matrix

假设您想要n行和m列。零表是一个所有值等于零的表。您想要创建维度nm的零表。如何在SQL Server 2014中创建维度为nm的零表?

2 个答案:

答案 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