2009-12-22 15 views
33

Sto provando a stampare un valore selezionato, è possibile?SQL Server PRINT SELECT (Stampa un risultato di selezione della query)?

Esempio:

PRINT 
    SELECT SUM(Amount) FROM Expense 
+0

Shimmy - grazie per aver scelto la mia risposta come "la" risposta. –

+0

La domanda posta sulla stampa di un valore non sulla stampa di una tabella o di un set di risultati. In entrambi i casi, la lingua non consente una query secondaria come argomento per il comando PRINT. [Ecco un'altra domanda e risposta SO] (https://stackoverflow.com/a/5193984/3368958) che mostra un esempio molto simile a questo con riferimento alla documentazione di PRINT. –

risposta

55

Sai, ci potrebbe essere un modo più semplice, ma la prima cosa che viene in mente è:

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

È possibile, ovviamente, stampare qualsiasi numero di campi dalla tabella in questo modo. Ovviamente, se desideri stampare tutti i risultati di una query che restituisce più righe, devi semplicemente indirizzare l'output in modo appropriato (ad esempio, in Testo).

+0

Questo di solito è il modo migliore, ma per una buona soluzione quando hai un sacco di righe e colonne che vuoi scaricare con 'print' vedi la risposta @DanFields qui sotto - http://stackoverflow.com/a/36729681/8479 – Rory

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

Se si desidera stampare più righe, è possibile scorrere il risultato utilizzando un cursore. ad es. stampare tutti i nomi da 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

ho scritto questo SP per fare proprio quello che si vuole, tuttavia, è necessario utilizzare SQL dinamico.

questo ha funzionato per me su 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 

Questo ha funzionato per me su 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 

Questo ha funzionato per me su 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 

Esempio:

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

Questo SP non funziona, qualunque query fornisca dice 'sintassi errata vicino a 'mia query'' –

+0

Questo funziona per me su SQL Server 2014. Testare ora altre versioni. –

+0

Aggiornato il post per includere le versioni di lavoro su R2 2008, 2012 e 2014. –

25

Se sei OK con la visualizzazione di esso come XML:

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

Mentre domanda del PO, come ha chiesto non richiede necessariamente questo, è utile se sei stato qui in cerca di stampare più righe/colonne (in un raggio ragionare).

+1

Questo è _amazing_!Ci sono così tanti casi in cui si vorrebbe usare 'PRINT' per scaricare i risultati e l'aggiunta di un proc personalizzato è troppo faticoso. Ottima soluzione. – Rory

+0

Sì, l'ho usato in SSMS dove l'aggiunta di SELECT * FROM avrebbe causato problemi ad altre applicazioni/utenti. –

1

Prova questa ricerca

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

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