如何为SQL中的结果集中的每一行选择一个额外的行?

时间:2016-12-27 11:09:47

标签: sql sql-server

我有以下查询:

SELECT '['+name+']' FROM sys.schemas
Where name <> 'dbo' AND name <> 'guest' AND name <> 'INFORMATION_SCHEMA'
....

此查询的结果很简单:

Enter image description here

在每个记录之后我需要一个额外的行'GO':

Enter image description here

有办法做到这一点吗?我尝试使用foreach语句,但我无法复制所需的结果。

8 个答案:

答案 0 :(得分:24)

只需按Enter键将Go语句添加到动态代码中,然后在SSMS中查看粘贴的结果。这将填充下一行中的GO语句。

您还应该使用QUOTENAME而不是自己连接方括号(以便对包含]的名称正常工作),并且可以使用NOT IN简化where子句。

SELECT QUOTENAME(name) +'
GO
' 
FROM sys.schemas 
WHERE name NOT IN  ('dbo', 'guest', 'INFORMATION_SCHEMA') 

答案 1 :(得分:13)

您可以使用UNION ALL填充这些额外值,并使用CASE EXPRESSION子句中的ORDER BY来执行此特定订单:

SELECT t.name_col
FROM(
    SELECT '['+name+']' as name_col,'['+name+']' as ord_col
    FROM sys.schemas 
    Where name NOT IN('dbo','guest','INFORMATION_SCHEMA')
    UNION ALL 
    SELECT 'GO','['+name+']' as ord_col 
    FROM sys.schemas 
    Where name NOT IN('dbo','guest','INFORMATION_SCHEMA')) t
ORDER BY t.ord_col,
         CASE WHEN t.name_col = 'GO' THEN 1 ELSE 0 END

答案 2 :(得分:12)

如果你只想要回车和&#34; GO&#34;在每一行之后,您可以将其放在SELECT

SELECT '[' + name + ']
GO'
FROM sys.schemas 
Where name <> 'dbo' AND name <> 'guest' AND name <> 'INFORMATION_SCHEMA' 
....

这不是你要求的,但它可能会做你需要的。

答案 3 :(得分:6)

select  c.txt
from    sys.schemas cross apply (values ('['+name+']'),('GO')) c(txt)
where   name not in ('dbo','guest','INFORMATION_SCHEMA') 

保证订单

select      c.txt
from        sys.schemas s cross apply (values ('['+name+']',1),('GO',2)) c(txt,ord)
where       s.name not in ('dbo','guest','INFORMATION_SCHEMA') 
order by    s.name,c.ord

答案 4 :(得分:4)

以下是交叉应用值的另一种方法

SELECT B.*
FROM   (SELECT '[' + NAME + ']' AS NAME1,
               'GO'             AS GO1
        FROM   SYS.SCHEMAS
        WHERE  NAME NOT IN ( 'DBO', 'GUEST', 'INFORMATION_SCHEMA' ))A
       CROSS APPLY ( VALUES(NAME1),
                           (GO1) ) B(NAME1) 

答案 5 :(得分:2)

列中的新行显示:

SELECT QUOTENAME(name)+CHAR(10)+CHAR(13)+'GO' 
FROM sys.schemas 
WHERE name <> 'dbo' AND name <> 'guest' AND name <> 'INFORMATION_SCHEMA';

换行新行:

SELECT
    lot
FROM
    (
        SELECT name=CAST(QUOTENAME(name) AS VARCHAR(256)),extra_line=CAST('GO' AS VARCHAR(256))
        FROM sys.schemas
        WHERE name <> 'dbo' AND name <> 'guest' AND name <> 'INFORMATION_SCHEMA'
    ) as p
    UNPIVOT(lot FOR l IN (name,extra_line)) AS up;

答案 6 :(得分:1)

如下:

select name from (
SELECT 2 * rowid as r, 
    '['+name+']' as name
    FROM sys.schemas 
union
select 2 * rowid + 1, 'GO' FROM sys.schemas 
)s
order by r

答案 7 :(得分:1)

对于CONCAT

,我们也可以使用+而不是SQL2008+
SELECT CONCAT('[', name ,'] GO ')
FROM sys.schemas 
WHERE name <> 'dbo' AND name <> 'guest' AND name <> 'INFORMATION_SCHEMA';