在SELECT状态项中使用While

时间:2018-08-04 14:18:28

标签: sql-server

我的目标是创建许多带有空单元格的列。

基本上,这只是具有定义的列数:

SELECT NOM_EMP,PRENOM_EMP, '' as [1], '' as [2] 
FROM EMPLOYE

我已经尝试过了,但是没有用:

DECLARE @I AS INT

SET @I = 10

SELECT 
    ROW_NUMBER() OVER (ORDER BY NOM_EMP)  as 'Number', NOM_EMP, Prenom_EMP, 
    WHILE @I < 10
    BEGIN
         SELECT '' AS
    END 
FROM EMPLOYE

那有可能实现吗?

预期结果:(假设我在循环中使用8)

enter image description here

2 个答案:

答案 0 :(得分:1)

一种方法是使用动态SQL,使用XML PATH构建列列表:

DECLARE
      @SQL nvarchar(MAX)
    , @i int = 10;

WITH 
     t10 AS (SELECT n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) t(n))
    ,t1000 AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS i FROM t10 AS a CROSS JOIN t10 AS b CROSS JOIN t10 AS c)
SELECT @SQL = 'SELECT NOM_EMP,PRENOM_EMP,' + 
    STUFF((SELECT ','''' AS ' + QUOTENAME(CAST(i AS nvarchar(4)))
    FROM t1000
    WHERE i < @i
    FOR XML PATH(''), TYPE).value('.','nvarchar(MAX)'),1,1,'')
    + N' from EMPLOYE';
EXECUTE sp_executesql @SQL;

在SQL Server 2017和更高版本中,您可以使用替代项STRING_AGG

答案 1 :(得分:0)

SQL Server在设计上是声明性的,不支持宏替换。

这留下了动态SQL

示例

Declare @Int int = 8

Declare @SQL varchar(max) = '
Select NOM_EMP,PRENOM_EMP,'
+ (Select Stuff((Select ',[' +cast(N as varchar(25))+']=''''' 
                From (Select Top (@Int) N=Row_Number() Over (Order By (Select NULL)) From master..spt_values n1) A
                For XML Path ('')),1,1,'')
   )
+ ' From Employee'

Exec(@SQL)

生成的SQL

Select NOM_EMP,PRENOM_EMP,[1]='',[2]='',[3]='',[4]='',[5]='',[6]='',[7]='',[8]='' 
 From Employee