1

有什么方法可以在 SQL Server 中执行查询,然后打印一条包含查询结果数据的消息。

例如,如果我有这样的查询:

SELECT ID, FirstName, LastName FROM Customers

对于结果的每一行,我想用这样的东西来跟踪它。

Print N'Customer ID: ' + [ID]
Print N'First Name: ' + [FirstName]
Print N'Last Name: ' + [LastName]

我知道我可以使用该AS子句来格式化每一列,但数据将始终在表格中格式化。有没有办法在不使用另一种语言处理结果的情况下以不同的方式格式化结果?

4

3 回答 3

2

您可以使用光标:

declare @curse cursor
set @curse = cursor fast_forward for
select ID, FirstName, LastName
from Customers

declare @id int,
        @firstName varchar(32),
        @lastName varchar(32)

open @curse

fetch next from @curse into @id, @firstName, @lastName

while (@@fetch_status = 0)
begin
    Print N'Customer ID: ' + @id
    Print N'First Name: ' + @firstName
    Print N'Last Name: ' + @lastName

    fetch next from @curse into @id, @firstName, @lastName
end

close @curse

或者你可以不这样做:

select 'Customer ID: ' + cast(ID as varchar(32)) + char(13) + char(10) + 
       'First Name: ' + FirstName + char(13) + char(10) + 
       'Last Name: ' + LastName + char(13) + char(10)
from Customers

如果您使用Ctrl + T第二种方式,用于将 SSMS 中的输出从网格模式更改为文本模式。

于 2013-04-20T15:23:32.300 回答
1

你可以试试这个:

DECLARE @customerid varchar(100);
DECLARE @firstname varchar(100);
DECLARE @@lastname varchar(100);

SELECT @customerid=ID, @firstname=FirstName, @lastname=LastName 
FROM Customers

Print N'Customer ID: ' + @customerid
Print N'First Name: ' +  @firstname
Print N'Last Name: ' + @lastname
于 2013-04-20T15:20:36.203 回答
0

如果您只需要数据的垂直格式,那么我仍然建议使用 SELECT 而不是 PRINT:

SELECT Lbl, Txt
FROM (
              SELECT ID, 'Customer ID:' As Lbl, CAST(ID As VARCHAR(50)) As Txt       FROM Customers
    UNION ALL SELECT ID, 'First Name:' As Lbl, CAST(FirstName As VARCHAR(50)) As Txt FROM Customers
    UNION ALL SELECT ID, 'Last Name:' As Lbl, CAST(FirstName As VARCHAR(50)) As Txt  FROM Customers
    ) A
ORDER BY ID, Lbl
于 2013-04-20T15:36:56.373 回答