将空行添加到结果中

时间:2015-08-06 08:11:44

标签: sql sql-server

我想在从select语句中获取的结果中添加空行。例如,如果select查询获取4行,则需要获取2个空行。目标应该是每次提取的行数应该是6。如果有6行数据,则获取的行数最多为6。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

SQL-SERVER 中您可以创建临时表以使用空行更新它,并且可以使用WHILE插入具有空值的所需行数。类似的东西:

-- Create temp table to update data with empty rows
CREATE TABLE #HoldEmptyRows
(
   Id NVARCHAR(20), 
   CustomerName NVARCHAR(20), 
   CustomerEmail NVARCHAR(20)
)

-- Insert data from SourceTable to temp
INSERT INTO #HoldEmptyRows
SELECT * FROM SourceTable

-- Do while count from temp table < of desired number insert empty rows
WHILE ((SELECT COUNT(*) cnt FROM #HoldEmptyRows) < 6)
BEGIN
   INSERT INTO #HoldEmptyRows VALUES ('', '', '')
END

SELECT * FROM #HoldEmptyRows

DEMO AT SQL FIDDLE

答案 1 :(得分:0)

尝试以下逻辑:

with cte as
(
select 0 as col1
union all
select col1+1 from cte where cte.col1<10
)

select * into #temp1 from cte


create table #test
(rownum int,col1 varchar(100))


declare @i int=1
while (@i<=6)
begin

insert into #test
select *   from 
(select row_Number() over (order by (Select 0))rownum, * from #temp1)x
where rownum=@i 

Set @i=@i+1
end
select case when rownum>4 then '' else col1 end as col1 from #test