2009-12-22 115 views
33

我想打印一個選定的值,這可能嗎?SQL Server PRINT SELECT(打印選擇查詢結果)?

例子:

PRINT 
    SELECT SUM(Amount) FROM Expense 
+0

擺振 - 感謝選擇我的答案爲「」的答案。 – 2009-12-22 03:17:30

+0

有關打印值而不是打印表格或結果集的問題。無論哪種情況,語言都不允許將子查詢作爲PRINT命令的參數。 [這是另一個SO問題和答案](https://stackoverflow.com/a/5193984/3368958),它顯示了一個非常類似於參考PRINT文檔的例子。 – 2016-11-30 19:26:14

回答

55

你知道,有可能是一個更簡單的方法,但彈出想到的第一件事是:

Declare @SumVal int; 
Select @SumVal=Sum(Amount) From Expense; 
Print @SumVal; 

你可以,當然,打印任何以這種方式從表中的字段數量。當然,如果要打印返回多行的查詢的所有結果,則只需將輸出適當地引導(例如,輸入到文本)。

+0

這通常是最好的方法,但是當您有大量要使用'print'轉儲出來的行和列時,請參閱下面的@DanFields答案以獲得一個很好的解決方案 - http://stackoverflow.com/a/36729681/8479 – Rory 2016-04-24 20:02:13

6
set @n = (select sum(Amount) from Expense) 
print 'n=' + @n 
20

如果要打印多行,可以使用遊標遍歷結果。 例如從sys.database_principals

DECLARE @name nvarchar(128) 

DECLARE cur CURSOR FOR 
SELECT name FROM sys.database_principals 

OPEN cur 

FETCH NEXT FROM cur INTO @name; 
WHILE @@FETCH_STATUS = 0 
BEGIN 
PRINT @name 
FETCH NEXT FROM cur INTO @name; 
END 

CLOSE cur; 
DEALLOCATE cur; 
2

我寫你想要的東西,這個SP做打印所有的名字,但是,你需要使用動態SQL。

這爲我工作的SQL Server 2008 R2上

ALTER procedure [dbo].[PrintSQLResults] 
    @query nvarchar(MAX), 
    @numberToDisplay int = 10, 
    @padding int = 20 
as 

SET NOCOUNT ON; 
SET ANSI_WARNINGS ON; 

declare @cols nvarchar(MAX), 
     @displayCols nvarchar(MAX), 
     @sql nvarchar(MAX), 
     @printableResults nvarchar(MAX), 
     @NewLineChar AS char(2) = char(13) + char(10), 
     @Tab AS char(9) = char(9); 

if exists (select * from tempdb.sys.tables where name = '##PrintSQLResultsTempTable') drop table ##PrintSQLResultsTempTable 

set @query = REPLACE(@query, 'from', ' into ##PrintSQLResultsTempTable from'); 
--print @query 
exec(@query); 
select ROW_NUMBER() OVER (ORDER BY (select Null)) AS ID12345XYZ, * into #PrintSQLResultsTempTable 
from ##PrintSQLResultsTempTable 
drop table ##PrintSQLResultsTempTable 

select name 
into #PrintSQLResultsTempTableColumns 
from tempdb.sys.columns where object_id = 
object_id('tempdb..#PrintSQLResultsTempTable'); 

select @cols = 
stuff((
    (select ' + space(1) + (LEFT((CAST([' + name + '] as nvarchar(max)) + space('+ CAST(@padding as nvarchar(4)) +')), '+CAST(@padding as nvarchar(4))+')) ' as [text()] 
    FROM #PrintSQLResultsTempTableColumns 
    where name != 'ID12345XYZ' 
    FOR XML PATH(''), root('str'), type).value('/str[1]','nvarchar(max)')) 
,1,0,''''''); 

select @displayCols = 
stuff((
    (select space(1) + LEFT(name + space(@padding), @padding) as [text()] 
    FROM #PrintSQLResultsTempTableColumns 
    where name != 'ID12345XYZ' 
    FOR XML PATH(''), root('str'), type).value('/str[1]','nvarchar(max)')) 
,1,0,''); 

DECLARE 
    @tableCount int = (select count(*) from #PrintSQLResultsTempTable); 
DECLARE 
    @i int = 1, 
    @ii int = case when @tableCount < @numberToDisplay then @tableCount else @numberToDisplay end; 

print @displayCols -- header 
While @i <= @ii 
BEGIN 
    set @sql = N'select @printableResults = ' + @cols + ' + @NewLineChar from #PrintSQLResultsTempTable where ID12345XYZ = ' + CAST(@i as varchar(3)) + '; print @printableResults;' 
    --print @sql 
    execute sp_executesql @sql, N'@NewLineChar char(2), @printableResults nvarchar(max) output', @NewLineChar = @NewLineChar, @printableResults = @printableResults output 
    print @printableResults 
    SET @i += 1; 
END 

這爲我工作的SQL Server 2012

ALTER procedure [dbo].[PrintSQLResults] 
    @query nvarchar(MAX), 
    @numberToDisplay int = 10, 
    @padding int = 20 
as 

SET NOCOUNT ON; 
SET ANSI_WARNINGS ON; 

declare @cols nvarchar(MAX), 
     @displayCols nvarchar(MAX), 
     @sql nvarchar(MAX), 
     @printableResults nvarchar(MAX), 
     @NewLineChar AS char(2) = char(13) + char(10), 
     @Tab AS char(9) = char(9); 

if exists (select * from tempdb.sys.tables where name = '##PrintSQLResultsTempTable') drop table ##PrintSQLResultsTempTable 

set @query = REPLACE(@query, 'from', ' into ##PrintSQLResultsTempTable from'); 
--print @query 
exec(@query); 
select ROW_NUMBER() OVER (ORDER BY (select Null)) AS ID12345XYZ, * into #PrintSQLResultsTempTable 
from ##PrintSQLResultsTempTable 
drop table ##PrintSQLResultsTempTable 

select name 
into #PrintSQLResultsTempTableColumns 
from tempdb.sys.columns where object_id = 
object_id('tempdb..#PrintSQLResultsTempTable'); 

select @cols = 
stuff((
    (select ' + space(1) + LEFT(CAST([' + name + '] as nvarchar('+CAST(@padding as nvarchar(4))+')) + space('+ CAST(@padding as nvarchar(4)) +'), '+CAST(@padding as nvarchar(4))+') ' as [text()] 
    FROM #PrintSQLResultsTempTableColumns 
    where name != 'ID12345XYZ' 
    FOR XML PATH(''), root('str'), type).value('/str[1]','nvarchar(max)')) 
,1,0,''''''); 

select @displayCols = 
stuff((
    (select space(1) + LEFT(name + space(@padding), @padding) as [text()] 
    FROM #PrintSQLResultsTempTableColumns 
    where name != 'ID12345XYZ' 
    FOR XML PATH(''), root('str'), type).value('/str[1]','nvarchar(max)')) 
,1,0,''); 

DECLARE 
    @tableCount int = (select count(*) from #PrintSQLResultsTempTable); 
DECLARE 
    @i int = 1, 
    @ii int = case when @tableCount < @numberToDisplay then @tableCount else @numberToDisplay end; 

print @displayCols -- header 
While @i <= @ii 
BEGIN 
    set @sql = N'select @printableResults = ' + @cols + ' + @NewLineChar from #PrintSQLResultsTempTable where ID12345XYZ = ' + CAST(@i as varchar(3)) + ' ' 
    --print @sql 
    execute sp_executesql @sql, N'@NewLineChar char(2), @printableResults nvarchar(max) output', @NewLineChar = @NewLineChar, @printableResults = @printableResults output 
    print @printableResults 
    SET @i += 1; 
END 

這爲我工作的SQL Server 2014年

ALTER procedure [dbo].[PrintSQLResults] 
    @query nvarchar(MAX), 
    @numberToDisplay int = 10, 
    @padding int = 20 
as 

SET NOCOUNT ON; 
SET ANSI_WARNINGS ON; 

declare @cols nvarchar(MAX), 
     @displayCols nvarchar(MAX), 
     @sql nvarchar(MAX), 
     @printableResults nvarchar(MAX), 
     @NewLineChar AS char(2) = char(13) + char(10), 
     @Tab AS char(9) = char(9); 

if exists (select * from tempdb.sys.tables where name = '##PrintSQLResultsTempTable') drop table ##PrintSQLResultsTempTable 

set @query = REPLACE(@query, 'from', ' into ##PrintSQLResultsTempTable from'); 
--print @query 
exec(@query); 
select ROW_NUMBER() OVER (ORDER BY (select Null)) AS ID12345XYZ, * into #PrintSQLResultsTempTable 
from ##PrintSQLResultsTempTable 
drop table ##PrintSQLResultsTempTable 

select name 
into #PrintSQLResultsTempTableColumns 
from tempdb.sys.columns where object_id = 
object_id('tempdb..#PrintSQLResultsTempTable'); 

select @cols = 
stuff((
    (select ' , space(1) + LEFT(CAST([' + name + '] as nvarchar('+CAST(@padding as nvarchar(4))+')) + space('+ CAST(@padding as nvarchar(4)) +'), '+CAST(@padding as nvarchar(4))+') ' as [text()] 
    FROM #PrintSQLResultsTempTableColumns 
    where name != 'ID12345XYZ' 
    FOR XML PATH(''), root('str'), type).value('/str[1]','nvarchar(max)')) 
,1,0,''''''); 

select @displayCols = 
stuff((
    (select space(1) + LEFT(name + space(@padding), @padding) as [text()] 
    FROM #PrintSQLResultsTempTableColumns 
    where name != 'ID12345XYZ' 
    FOR XML PATH(''), root('str'), type).value('/str[1]','nvarchar(max)')) 
,1,0,''); 

DECLARE 
    @tableCount int = (select count(*) from #PrintSQLResultsTempTable); 
DECLARE 
    @i int = 1, 
    @ii int = case when @tableCount < @numberToDisplay then @tableCount else @numberToDisplay end; 

print @displayCols -- header 
While @i <= @ii 
BEGIN 
    set @sql = N'select @printableResults = concat(@printableResults, ' + @cols + ', @NewLineChar) from #PrintSQLResultsTempTable where ID12345XYZ = ' + CAST(@i as varchar(3)) 
    --print @sql 
    execute sp_executesql @sql, N'@NewLineChar char(2), @printableResults nvarchar(max) output', @NewLineChar = @NewLineChar, @printableResults = @printableResults output 
    print @printableResults 
    SET @printableResults = null; 
    SET @i += 1; 
END 

例如:

exec [dbo].[PrintSQLResults] n'select * from MyTable' 
+0

這個SP不起作用,無論我給它的查詢是什麼說'我的查詢附近有不正確的語法' – 2016-02-21 08:49:58

+0

這適用於SQL Server 2014上的我。現在測試其他版本。 – 2016-02-22 16:26:10

+0

已更新該帖子以包含2008 R2,2012和2014版本的工作版本。 – 2016-02-22 16:54:16

25

如果你用它看作XML OK:

DECLARE @xmltmp xml = (SELECT * FROM table FOR XML AUTO) 
PRINT CONVERT(NVARCHAR(MAX), @xmltmp) 

雖然作爲問OP的問題並不一定需要這個,這是如果你來到這裏尋找到打印多行/列(內有用原因)。

+1

這是_amazing_!有很多情況下,您想使用'PRINT'來轉儲結果併爲其添加自定義過程是非常困難的工作。好的解決方案 – Rory 2016-04-24 19:53:47

+0

是的,我已經在SSMS中使用了這種方法,其中添加SELECT * FROM會導致其他應用程序/用戶出現問題。 – 2016-04-25 00:05:13

1

嘗試此查詢

DECLARE @PrintVarchar nvarchar(max) = (Select Sum(Amount) From Expense) 
PRINT 'Varchar format =' + @PrintVarchar 

DECLARE @PrintInt int = (Select Sum(Amount) From Expense) 
PRINT @PrintInt