2009-12-22 203 views
33

Estoy tratando de imprimir un valor seleccionado, ¿es esto posible?SQL Server PRINT SELECT (¿Imprimir un resultado de consulta seleccionado)?

Ejemplo:

PRINT 
    SELECT SUM(Amount) FROM Expense 
+0

Shimmy - gracias por seleccionar mi respuesta como "la" respuesta. –

+0

La pregunta sobre la impresión de un valor no se trata de imprimir una tabla o un conjunto de resultados. En cualquier caso, el lenguaje no permite una sub consulta como argumento para el comando PRINT. [Aquí hay otra pregunta y respuesta de SO] (https://stackoverflow.com/a/5193984/3368958) que muestra un ejemplo muy similar a este con referencia a la documentación de IMPRESIÓN. –

Respuesta

55

Usted sabe, puede haber una manera más fácil, pero el primero que le viene a la mente es:

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

Puede, por supuesto, imprimir cualquier número de campos de la tabla de esta manera. Por supuesto, si desea imprimir todos los resultados de una consulta que devuelve varias filas, simplemente dirija su salida de forma adecuada (por ejemplo, a Texto).

+0

Por lo general, esta es la mejor manera, pero para una buena solución cuando tiene muchas filas y columnas que desea eliminar con 'print', consulte la respuesta @DanFields a continuación - http://stackoverflow.com/a/36729681/8479 – Rory

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

Si desea imprimir varias filas, puede recorrer el resultado con un cursor. p. imprimir todos los nombres de 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

que escribí este SP para hacer exactamente lo que quiere, sin embargo, es necesario utilizar SQL dinámico.

Esto funcionó para mí en 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 

Esto funcionó para mí en 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 

Esto funcionó para mí en 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 

Ejemplo:

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

Este SP no funciona, cualquiera que sea la consulta que le doy dice 'sintaxis incorrecta cerca de 'mi consulta'' –

+0

Esto funciona para mí en el servidor SQL 2014. Probando ahora otras versiones. –

+0

Actualicé la publicación para incluir las versiones en funcionamiento en 2008 R2, 2012 y 2014. –

25

Si estás bien con viéndolo como XML:

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

Mientras que la pregunta de la OP como pidió no requiere necesariamente esto, es útil si llegamos aquí buscando para imprimir varias filas/columnas (dentro de razón).

+1

¡Esto es _amazing_!Hay tantos casos en los que desearía usar 'PRINT' para eliminar resultados y agregar un proceso personalizado porque es demasiado trabajo. Gran solución – Rory

+0

Sí, he usado esto en SSMS donde agregar un SELECT * FROM podría causar problemas para otras aplicaciones/usuarios. –

1

Intentar esta consulta

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

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