Below code works fine and convert table to HTML. It gives the results as HTML tables but I want to assign this to a variable
How can we assign the output to a variable in below code.
CREATE PROC dbo.usp_ConvertQuery2HTMLTable (
#SQLQuery NVARCHAR(3000))
AS
BEGIN
DECLARE #columnslist NVARCHAR (1000) = ''
DECLARE #restOfQuery NVARCHAR (2000) = ''
DECLARE #DynTSQL NVARCHAR (3000)
DECLARE #FROMPOS INT
DECLARE #out table
(
out nvarchar(max)
)
SET NOCOUNT ON
SELECT #columnslist += 'ISNULL (' + NAME + ',' + '''' + ' ' + '''' + ')' + ','
FROM sys.dm_exec_describe_first_result_set(#SQLQuery, NULL, 0)
SET #columnslist = left (#columnslist, Len (#columnslist) - 1)
SET #FROMPOS = CHARINDEX ('FROM', #SQLQuery, 1)
SET #restOfQuery = SUBSTRING(#SQLQuery, #FROMPOS, LEN(#SQLQuery) - #FROMPOS + 1)
SET #columnslist = Replace (#columnslist, '),', ') as TD,')
SET #columnslist += ' as TD'
SET #DynTSQL = CONCAT (
'SELECT (SELECT '
, #columnslist
,' '
, #restOfQuery
,' FOR XML RAW (''TR''), ELEMENTS, TYPE) AS ''TBODY'''
,' FOR XML PATH (''''), ROOT (''TABLE'')'
)
PRINT #DynTSQL
EXEC (#DynTSQL)
SET NOCOUNT OFF
END
Generally, you have 2 options.
Via an intermediate temporary table (table variable).
By itself, exec() returns nothing when a literal or variable is executed, but you can use the rowset produced by it as a source for an insert statement:
-- Option 1
declare #t table (X xml);
declare #Ret xml;
insert into #t (X)
exec('select top 1 * from sys.objects o for xml raw(''TR''), elements, type;');
select top (1) #Ret = t.X from #t t;
select #Ret as [Option1];
go
Switching to the sys.sp_executesql
As Peter has suggested in the comments, you can switch from exec to the sp_executesql system stored procedure, which provides an additional functionality of output parameters:
-- Option 2
declare #s nvarchar(max) = N'set #A = (select top 1 * from sys.objects o for xml raw(''TR''), elements, type);';
declare #Ret xml;
exec sys.sp_executesql #s, N'#A xml = null output', #A = #Ret output;
select #Ret as [Option2];
go
Related
I wonder that;
in SQl, is it possible to not bring the columns which have no data (or zero value)?
Select * from PLAYER_TABLE where PLAYER_NAME='cagri'
it is bringing just 1 row. because there is only one player which PLAYER_NAME is "cagri".
And there are 30 columns for example statistics.
Score-Rebound-PlayedMinutes-Fauls etc....
Score=2
Rebound=0
PlayedMinutes=2
Fauls=0
and I want to see only [Score] and [PlayedMinutes] columns when call my query.
is it possible?
You can use this logic over a stored procedure in SQL
DDL
create table usr_testtable
(player varchar(30),col1 float, col2 float, col3 float, col4 float)
insert into usr_testtable
values ('Jordan',10,20,3,0)
Convert to Stored Proc
declare #playername varchar(30) = 'Jordan' --- pass this value
declare #ctr smallint = 2 -- start from ordinal 2
declare #maxctr smallint = (SELECT max(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'usr_testTable')
declare #columns varchar(max) = ''
declare #columnswithvalues varchar(max) = ''
declare #coltocheck varchar(30)
declare #mysql nvarchar(max)
declare #coloutput varchar(30)
while #ctr <= #maxctr
begin
SELECT #coltocheck = COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'usr_testTable'
and ORDINAL_POSITION = #ctr
set #mysql = N'select #output = ' + #coltocheck + ' from usr_testTable where player =''' + #playername + ''' and cast(' + #coltocheck +' as float) > 0'
EXECUTE sp_executesql #mysql,N'#output int OUTPUT',#output = #coloutput OUTPUT;
if #coloutput > 0
begin
set #columns = coalesce(#columns + ',' + #coltocheck,#columns)
set #columnswithvalues = coalesce(#columnswithvalues + char(13) + char(10) + #coltocheck + ' : ' + #coloutput,#columnswithvalues) --- text form
end
set #coloutput = ''
set #ctr= #ctr + 1
end
-- final result in table format
set #mysql = N'select player' + #columns + ' from usr_testTable where player =''' + #playername + ''' '
EXECUTE sp_executesql #mysql
-- final result in text format appended with columnname
select #columnswithvalues -- format to display in text
First create dynamic SQL to select all columns names in the table PLAYER_TABLE except PLAYER_NAME, then unpivot data from PLAYER_TABLE into table PLAYER_TABLE1, then you can search values <> 0 and select this column in second dynamic SQL.
DROP TABLE PLAYER_TABLE1
DECLARE #Player NVARCHAR(50);
DECLARE #columns NVARCHAR(max);
DECLARE #sql NVARCHAR(max);
DECLARE #columns2 NVARCHAR(max);
DECLARE #sql2 NVARCHAR(max);
SET #player='cagri'
SET #columns = Stuff((SELECT ','
+ Quotename(Rtrim(Ltrim(x.columns)))
FROM (SELECT COLUMN_NAME as columns FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME= 'PLAYER_TABLE' and COLUMN_NAME<>'PLAYER_NAME' ) AS x
ORDER BY X.columns
FOR xml path('')), 1, 1, '');
SET #sql = N' SELECT
PLAYER_NAME, Un_Pivot.Field, Un_Pivot.Value
INTO PLAYER_TABLE1
FROM
(
SELECT * FROM PLAYER_TABLE
) Data
UNPIVOT
(
Value FOR Field IN ('+#columns+')
) AS Un_Pivot';
EXECUTE sp_executesql #sql;
SET #columns2 = Stuff((SELECT ','
+ Quotename(Rtrim(Ltrim(y.Field)))
FROM (SELECT Field FROM PLAYER_TABLE1 WHERE VALUE<>0 AND PLAYER_NAME=#Player) AS y
ORDER BY y.Field
FOR xml path('')), 1, 1, '');
SET #sql2 = N'SELECT PLAYER_NAME,'+#columns2+'FROM PLAYER_TABLE WHERE PLAYER_NAME='+char(39)+#Player+char(39);
EXECUTE sp_executesql #sql2
I am running a SQL loop to update a declared table. Please have a look at the following
DECLARE #tblResults TABLE ( [idx] INT IDENTITY(0,1)
,[cityCode] VARCHAR(3)
,[month_1_perc] INT
,[month_2_perc] INT
,[month_3_perc] INT
,[month_4_perc] INT
,[month_5_perc] INT
,[month_6_perc] INT
,[month_7_perc] INT
,[month_8_perc] INT
,[month_9_perc] INT
,[month_10_perc] INT
,[month_11_perc] INT
,[month_12_perc] INT)
loop will start here
DECLARE #colName VARCHAR(15)
DECLARE #sqlExec VARCHAR(500) = CONACT('UPDATE #tblResults SET [month_', #colName, '_perc] = 9;
EXECUTE(#sql)
loop
This obviously doesn't work - I am trying to find a work around if any -
Open to suggestions
DECLARE #colName VARCHAR(15)
DECLARE #sqlExec VARCHAR(500)
SET #colName = '1'
SET #sqlExec = 'UPDATE #tblResults SET [month_' + #colName + '_perc] = 9'
EXECUTE( #sqlExec)
I am a bit confused with your request, but if you really want to use a loop
declare #i int = 1;
declare #sqlUpdate nvarchar(max) = 'UPDATE tblResults SET ';
declare #sql;
while #i <= 12
BEGIN
set #sql = #sqlUpdate + '[month_' + cast(#i as nvarchar(5)) + '_perc] = 9;' -- value?
print (#sql)
-- execute (#sql)
set #i = #i + 1;
END
Or you want to set same value to all columns in one go
declare #cols nvarchar(max)
select #cols = STUFF((SELECT ',' + QUOTENAME(col.name) + ' = 9' -- value?
from tempdb.sys.columns col
join tempdb.sys.tables tab on col.object_id = tab.object_id
where tempdb.tab.name = 'tblResults'
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
declare #sql nvarchar(max) = 'UPDATE tblResults SET ' + #cols;
print (#sql)
-- execute (#sql)
Note, none of scripts are tested
I have a master table which contains the table names and columns corresponding to that table.
I want to write a procedure which iterates through all the records of tables and gets all the data and returns it as a single result set.
You need to use Dynamic Query
DECLARE #sql VARCHAR(max)=''
SET #sql = (SELECT #sql + 'select ' + column_name + ' from '
+ table_name + ' union all '
FROM master_table
FOR xml path(''))
SELECT #sql = LEFT(#sql, Len(#sql) - 9)
EXEC (#sql)
Note : The datatype of all the columns should be same. If it is not the case then you may have to do explicit conversion to varchar
SET #sql = (SELECT #sql + 'select cast(' + column_name + ' as varchar(4000)) from '
+ table_name
+ ' union all '
FROM Master_table
FOR xml path(''))
Assuming that all tables listed in your Master table is having same columns with same order and data types. Then it will be as follows:
create table ##a
(
Value int
)
create table ##b
(
Value int
)
create table ##c
(
Value int
)
declare #all table
(
Value int
)
declare #master table
(
TableName varchar(10)
)
declare #TableName varchar(10)
insert ##a values (1), (2), (3)
insert ##b values (4), (5), (6)
insert ##c values (7), (8), (9)
insert #master values ('##a'), ('##b'),('##c')
declare looper cursor local static forward_only read_only for
select TableName from #master
open looper
fetch next from looper into #TableName
while ##fetch_status = 0
begin
insert #all exec('select Value from ' + #TableName)
fetch next from looper into #TableName
end
close looper
deallocate looper
select * from #all
drop table ##a
drop table ##b
drop table ##c
If the tables are of different structures, please visit Stored procedures and multiple result sets in T-SQL. It will squeeze the content of each table into a single XML cell. The article also explains how to read them back.
I assume that you are using many tables with different columns in your master table. You should loop your master table. Try like this,
DECLARE #sql NVARCHAR(max) = ''
DECLARE #start INT = 1
,#end INT = 0
,#tablename VARCHAR(100) = ''
DECLARE #TableList TABLE (
id INT identity(1, 1)
,tablename VARCHAR(128)
)
INSERT INTO #TableList (tablename)
SELECT DISTINCT table_name
FROM YourMasterTableName
WHERE TABLE_NAME = 'productss'
SET #end = ##ROWCOUNT
WHILE (#start <= #end)
BEGIN
SET #tablename = (
SELECT tablename
FROM #TableList
WHERE id = #start
)
SET #sql = (
SELECT ',[' + column_name + ']'
FROM YourMasterTableName M
WHERE TABLE_NAME = #tablename
FOR XML path('')
)
SET #sql = 'SELECT ' + stuff(#sql, 1, 1, '') + ' FROM ' + #tablename
EXEC sp_executesql #sql
SET #start = #start + 1
END
The following stored procedure works correctly execpt when I pass in the #NameSubstring parameter. I know I am not dynamically building the like clause properly. How can I build the like clause when this parameter also needs to be passed as a parameter in the EXEC sp_executesql call near the bottom of the procedure?
ALTER PROCEDURE [dbo].[spGetAutoCompleteList]
(
#AutoCompleteID int,
#StatusFlag int,
#NameSubstring varchar(100),
#CompanyID int,
#ReturnMappings bit,
#ReturnData bit
)
AS
DECLARE #ErrorCode int,
#GetMappings nvarchar(500),
#Debug bit,
#Select AS NVARCHAR(4000),
#From AS NVARCHAR(4000),
#Where AS NVARCHAR(4000),
#Sql AS NVARCHAR(4000),
#Parms AS NVARCHAR(4000)
SET #ErrorCode = 0
SET #Debug = 1
BEGIN TRAN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF #AutoCompleteID IS NOT NULL OR #StatusFlag IS NOT NULL OR #NameSubstring IS NOT NULL
BEGIN
SET #Select = '
SELECT ac.AutoCompleteID,
ac.AutoCompleteName,
ac.CompanyID,
ac.StatusFlag,
ac.OwnerOperID,
ac.CreateDT,
ac.CreateOperID,
ac.UpdateDT,
ac.UpdateOperID,
ac.SubmitOperID,
ac.SubmitDT,
ac.ReviewComments'
SET #GetMappings = '
Select ac.AutoCompleteID'
IF #ReturnData = 1
BEGIN
SET #Select = #Select + '
, ac.AutoCompleteData'
END
SET #From = '
FROM tbAutoComplete ac'
SET #Where = '
WHERE 1=1'
IF #AutoCompleteID IS NOT NULL
BEGIN
SET #Where = #Where + '
AND ac.AutoCompleteID = CAST(#AutoCompleteID AS nvarchar)'
END
IF #StatusFlag IS NOT NULL
BEGIN
SET #Where = #Where + '
AND ac.StatusFlag = CAST(#StatusFlag AS nvarchar)'
END
IF #NameSubstring IS NOT NULL
BEGIN
SET #Where = #Where + '
AND ac.AutoCompleteName like #NameSubstring' + '%'
END
SET #Where = #Where + '
AND ac.CompanyID = + CAST(#CompanyID AS nvarchar)'
SET #Sql = #Select + #From + #Where
SET #Parms = '
#AutoCompleteID int,
#StatusFlag int,
#NameSubstring varchar(100),
#CompanyID int'
EXEC sp_executesql #Sql,
#Parms,
#AutoCompleteID,
#StatusFlag,
#NameSubstring,
#CompanyID
IF #ReturnMappings = 1
BEGIN
SET #GetMappings = 'Select * FROM tbAutoCompleteMap acm WHERE acm.AutoCompleteID IN(' + #GetMappings + #From + #Where + ')'
--EXEC sp_executesql #GetMappings
END
IF #Debug = 1
BEGIN
PRINT #GetMappings
PRINT #Sql
END
END
SELECT #ErrorCode = #ErrorCode + ##ERROR
IF #ErrorCode <> 0
BEGIN
SELECT '<FaultClass>1</FaultClass><FaultCode>1</FaultCode>'
+ '<FaultDesc>Internal Database Error.</FaultDesc>'
+ '<FaultDebugInfo>(spGetAutoCompleteList): There was an error while trying to SELECT from tbAutoComplete.</FaultDebugInfo>'
ROLLBACK TRAN
RETURN
END
COMMIT TRAN
#NameString needs to be outside of the quotes. To get #NameString% enclosed in quotes, you use two single quotes to escape the quote character as a literal.
SET #Where = #Where + '
AND ac.AutoCompleteName like ''' + #NameSubstring + '%'''
To avoid SQL injection, do not use concatenation when adding the parameter to your SQL statement. I strongly recommend that you use this format:
IF #NameSubstring IS NOT NULL BEGIN
SET #Where += 'AND ac.AutoCompleteName LIKE #NameSubstring + char(37)'
END
By using char(37) instead of '%' you avoid having to escape the apostrophes around the string literal
If you wanted to put a wildcard at either side, then you would use
IF #NameSubstring IS NOT NULL BEGIN
SET #Where += 'AND ac.AutoCompleteName LIKE char(37) + #NameSubstring + char(37)'
END
-----------------------------------------------------------------------------
In case someone believes I am wrong, here's proof that concatenation is a risk.
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TestInjection]') AND type in (N'U')) BEGIN
create table TestInjection(ID int, Value nvarchar(10))
insert into TestInjection (ID,Value)
Values
(1,'Tom'),
(2,'Fred'),
(3,'Betty'),
(4,'Betty2'),
(5,'Betty3'),
(6,'George')
END
declare #NameSubstring nvarchar(1000) = 'Bet'
--declare #NameSubstring nvarchar(1000) = 'Bet%'';delete from TestInjection;select * from TestInjection where value = ''x'
declare #ID int = 2
Declare #sql nvarchar(1000) = 'select * from TestInjection where ID > #ID '
SET #sql +=' AND [Value] like ''' + #NameSubstring + '%'''
Declare #params nvarchar(100) = '#ID int'
exec sp_executesql #sql, #params, #ID
select * from TestInjection
Run it the first time and you will get a resultset with 3 records, and another with all 6 records.
Now swap the declaration of #NameSubstring to the alternative, and re-run. All data in the table has been deleted.
If on the other hand you write your code like:
declare #NameSubstring nvarchar(1000) = 'Bet'
--declare #NameSubstring nvarchar(1000) = 'Bet%'';delete from TestInjection;select * from TestInjection where value = ''x'
declare #ID int = 2
Declare #sql nvarchar(1000) = 'select * from TestInjection where ID > #ID '
SET #sql +=' AND [Value] LIKE #NameSubstring + char(37)'
Declare #params nvarchar(100) = '#ID int, #NameSubstring nvarchar(1000)'
exec sp_executesql #sql, #params, #ID, #NameSubstring
select * from TestInjection
Then you still get the 3 records returned the first time, but you don't lose your data when you change the declaration.
SET #Where = #Where + 'AND ac.AutoCompleteName like ''%' + #NameSubstring + '%'''
So, you are asking how to specify parameters when you use dynamic queries and sp_executesql ?
It can be done, like this:
DECLARE /* ... */
SET #SQLString = N'SELECT #LastlnameOUT = max(lname) FROM pubs.dbo.employee WHERE job_lvl = #level'
SET #ParmDefinition = N'#level tinyint, #LastlnameOUT varchar(30) OUTPUT'
SET #IntVariable = 35
EXECUTE sp_executesql #SQLString, #ParmDefinition, #level = #IntVariable, #LastlnameOUT=#Lastlname OUTPUT
You can read more about it here: http://support.microsoft.com/kb/262499
Perhaps this wouldn't be an issue if you weren't using dynamic SQL. It looks to me like a vanilla query would work just as well and be much more straightforward to read and debug. Consider the following:
SELECT ac.AutoCompleteID,
ac.AutoCompleteName,
ac.CompanyID,
ac.StatusFlag,
ac.OwnerOperID,
ac.CreateDT,
ac.CreateOperID,
ac.UpdateDT,
ac.UpdateOperID,
ac.SubmitOperID,
ac.SubmitDT,
ac.ReviewComments
FROM tbAutoComplete ac
WHERE ((ac.AutoCompleteID = CAST(#AutoCompleteID AS nvarchar) OR (#AutoCompleteID IS NULL))
AND ((ac.StatusFlag = CAST(#StatusFlag AS nvarchar)) OR (#StatusFlag IS NULL))
AND ((ac.AutoCompleteName like #NameSubstring + '%') OR (#NameSubstring IS NULL))
AND ((ac.CompanyID = CAST(#CompanyID AS nvarchar)) OR (#CompanyID IS NULL))
This is much simpler, clearer etc. Good luck!
I am trying to print a selected value, is this possible?
Example:
PRINT
SELECT SUM(Amount) FROM Expense
You know, there might be an easier way but the first thing that pops to mind is:
Declare #SumVal int;
Select #SumVal=Sum(Amount) From Expense;
Print #SumVal;
You can, of course, print any number of fields from the table in this way. Of course, if you want to print all of the results from a query that returns multiple rows, you'd just direct your output appropriately (e.g. to Text).
If you're OK with viewing it as XML:
DECLARE #xmltmp xml = (SELECT * FROM table FOR XML AUTO)
PRINT CONVERT(NVARCHAR(MAX), #xmltmp)
While the OP's question as asked doesn't necessarily require this, it's useful if you got here looking to print multiple rows/columns (within reason).
If you want to print multiple rows, you can iterate through the result by using a cursor.
e.g. print all names from 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;
set #n = (select sum(Amount) from Expense)
print 'n=' + #n
I wrote this SP to do just what you want, however, you need to use dynamic sql.
This worked for me on 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
This worked for me on 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
This worked for me on 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
Example:
exec [dbo].[PrintSQLResults] n'select * from MyTable'
Try this query
DECLARE #PrintVarchar nvarchar(max) = (Select Sum(Amount) From Expense)
PRINT 'Varchar format =' + #PrintVarchar
DECLARE #PrintInt int = (Select Sum(Amount) From Expense)
PRINT #PrintInt
If you want to print more than a single result, just select rows into a temporary table, then select from that temp table into a buffer, then print the buffer:
drop table if exists #temp
-- we just want to see our rows, not how many were inserted
set nocount on
select * into #temp from MyTable
-- note: SSMS will only show 8000 chars
declare #buffer varchar(MAX) = ''
select #buffer = #buffer + Col1 + ' ' + Col2 + CHAR(10) from #temp
print #buffer
Add
PRINT 'Hardcoded table name -' + CAST(##RowCount as varchar(10))
immediately after the query.
You can also use the undocumented sp_MSforeachtable stored procedure as such if you are looking to do this for every table:
sp_MSforeachtable #command1 ="PRINT 'TABLE NAME: ' + '?' DECLARE #RowCount INT SET #RowCount = (SELECT COUNT(*) FROM ?) PRINT #RowCount"
If you wish (like me) to have results containing mulitple rows of various SELECT queries "labelled" and can't manage this within the constraints of the PRINT statement in concert with the Messages tab you could turn it around and simply add messages to the Results tab per the below:
SELECT 'Results from scenario 1'
SELECT
*
FROM tblSample
Try this:
DECLARE #select as nvarchar(max) = ''
SELECT #select = #select + somefield + char(13) FROM sometable
PRINT #select