Conversion failed when converting date and/or time from character string? - sql-server

I use pivot table but when I execute I got this error please help me I am stuck on this thanks in advance sorry if any mistake and please also tell me that how to handle string in string in sql server I use " '' '',''-'' " but not sure it is correct or not please help me as soon as posible here are the query
SELECT #SQL = 'SELECT '
WHile #I <= #Months
BEGIN
SET #YearMonth = REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, DateAdd(Month, #I, #StartDate), 13), 3,9)), ' ', '-')
SET #ColumnText = #YearMonth
SET #SQL = #SQL + 'ISNULL([' + #YearMonth + '], 0.00) as ''' + #ColumnText + ''','
SET #I = #I +1
END
Set #I = 0
SET #SQL = #SQL + 'Product,Supplier,PackPrice,QuantityInPack,Code,SupplierID,Description,RebateAmount
FROM
(
SELECT p.NAME AS product,p.Code AS Code,P.Description as Description,oi.PackPrice,oi.QuantityInPack AS Packsize,S.ID AS SupplierID,s.[Name] AS Supplier,
CASE when oi.RebateType=2 then (oi.PackPrice*oi.RebateAmount)/100 ELSE oi.RebateAmount END AS RebateAmount ,o.Total as TotalSale,
REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, O.CreatedDate, 13), 3,9)), '' '',''-'') as tdate
FROM dbo.SCM_Product p WITH (NOLOCK)
INNER JOIN SCM_OrderItem oi WITH (NOLOCK) ON oi.ProductId = p.ID
LEFT OUTER JOIN dbo.SCM_Supplier s WITH(NoLock) ON oi.SupplierID=s.ID
LEFT OUTER JOIN SCM_Order o WITH (NOLOCK) ON o.Id = oi.ProductId AND O.Status <> 5 -- CANCELLED
AND O.Deleted = 0
WHERE ('''+#SupplierID+''' IS NULL OR s.ID IN (SELECT * FROM GetIDsTableFromIDsList(#SupplierID)))
AND ('''+#ProductID+''' IS NULL OR p.ID IN (SELECT * FROM GetIDsTableFromIDsList(#ProductID)) )
AND (o.CreatedDate >= '''+ dbo.GetDatePart(#StartDate) +''' AND o.CreatedDate <= '''+ dbo.GetDatePart(#Enddate) +''')
GROUP BY REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, o.CreatedDate, 13), 3,9)), '' '',''-''),
s.ID,p.Code,p.NAME,s.NAME,P.Description,oi.packPrice,oi.QuantityInPack,oi.RebateAmount,oi.RebateType,oi.PackPrice,o.Total
) SD
PIVOT
( SUM( SD.TotalSale) FOR SD.tdate IN ('
WHile #I <= #Months
BEGIN
SET #YearMonth = REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, DateAdd(Month, #I, #StartDate), 13), 3,9)), ' ', '-')
IF #I = #Months
BEGIN
SET #SQL = #SQL + ' [' + #YearMonth + ']'
END
ELSE
BEGIN
SET #SQL = #SQL + ' [' + #YearMonth + '],'
END
SET #I = #I +1
END
SET #SQL = #SQL + ')) as pvt
ORDER BY Supplier '
--EXEC(#SQL)
PRINT #SQL

The easiest way of doing it would be to use QUOTENAME() function,because you could easily miss quote in a large query.
Example:
DECLARE #name AS CHAR(10) = 'Revolver'
DECLARE #sql as NVARCHAR(300) = 'SELECT *
FROM Music.Album
WHERE Name ='+ QUOTENAME(#name,'''')
PRINT #sql;
or
DECLARE #name AS CHAR(10) = 'Revolver'
DECLARE #sql as NVARCHAR(300) = 'SELECT *
FROM Music.Album
WHERE Name ='''+ #name + ''''
PRINT #sql;

Related

Generate dynamic PATINDEX statement

I have the following two strings:
DECLARE #Str1 VARCHAR(MAX) = 'John A Mak|Street Road UAE'
DECLARE #Str2 VARCHAR(MAX) = '[First Name],[Last Name],[Middle Name]|[Address1],[Address2]'
Note: Both strings are dynamic may comes with more or less values.
Expected result: Want to if any of the given text present in the given columns using the PATINDEX. The following PATINDEX statement gonna used in the WHERE clause of the SELECT statement.
PATINDEX('John',[First Name]) + PATINDEX('A',[First Name]) + PATINDEX('Mak',[First Name]) +
PATINDEX('John',[Last Name]) + PATINDEX('A',[Last Name]) + PATINDEX('Mak',[Last Name]) +
PATINDEX('John',[Middle Name]) + PATINDEX('A',[Middle Name]) + PATINDEX('Mak',[Middle Name]) +
PATINDEX('Street',[Address1]) + PATINDEX('Road',[Address1]) + PATINDEX('UAE',[Address1]) +
PATINDEX('Street',[Address2]) + PATINDEX('Road',[Address2]) + PATINDEX('UAE',[Address2]) > 0
My try:
DECLARE #Str1 VARCHAR(MAX) = 'John A Mak|Street Road UAE'
DECLARE #Str2 VARCHAR(MAX) = '[First Name],[Last Name],[Middle Name]|[Address1],[Address2]'
DECLARE #Length int = 0
DECLARE #Length1 int = 0
DECLARE #Length2 int = 0
DECLARE #Position int = 0
DECLARE #Position1 int = 0
DECLARE #Position2 int = 0
DECLARE #Value varchar(max)
DECLARE #Value1 varchar(max)
DECLARE #Value2 varchar(max)
DECLARE #P_Str2 VARCHAR(MAX) = ''
DECLARE #P_Str3 VARCHAR(MAX) = ''
DECLARE #P_Str1 VARCHAR(MAX) = ''
DECLARE #FinalString VARCHAR(MAX) = ''
SET #P_Str1 = #Str1+'|';
SET #P_Str3 = #Str2+'|';
IF OBJECT_ID('tempdb..#tempt', 'U') IS NOT NULL DROP TABLE #tempt;
CREATE TABLE #tempt(keywords varchar(max));
WHILE CHARINDEX('|', #P_Str3, #Position2+1)>0
BEGIN
set #Length2 = CHARINDEX('|', #P_Str3, #Position2+1) - #Position2
set #Value2 = SUBSTRING(#P_Str3, #Position2, #Length2)
SET #P_Str2 = #Value2+',';
PRINT('--'+#P_Str2);
--WHILE LOOP for creating string for PAT INDEX
WHILE CHARINDEX(',', #P_Str2, #Position+1)>0
BEGIN
set #Length = CHARINDEX(',', #P_Str2, #Position+1) - #Position
set #Value = SUBSTRING(#P_Str2, #Position, #Length)
WHILE CHARINDEX('|', #P_Str1, #Position1+1)>0
BEGIN
set #Length1 = CHARINDEX('|', #P_Str1, #Position1+1) - #Position1
set #Value1 = SUBSTRING(#P_Str1, #Position1, #Length1)
PRINT('Value1--'+#Value1);
PRINT('Value--'+#Value);
INSERT INTO #tempt
SELECT DISTINCT split.a.value('.', 'VARCHAR(100)') AS Keywords
FROM
(
SELECT CAST ('<S>' + REPLACE(ltrim(rtrim(#Value1)), ' ', '</S><S>') + '</S>' AS XML) AS Element
) AS a
CROSS APPLY Element.nodes ('/S') AS split(a)
WHERE split.a.value('.', 'VARCHAR(100)') <> '';
SET #FinalString += STUFF(( SELECT '(PATINDEX('''+keywords+''','+#Value+'),''''0'''') + '
FROM #tempt FOR XML PATH('')), 1,0, '');
DELETE FROM #tempt;
SET #Position1 = CHARINDEX('|', #P_Str1, #Position1+#Length1) +1
END
SET #Position = CHARINDEX(',', #P_Str2, #Position+#Length) +1
END
SET #Position2 = CHARINDEX('|', #P_Str3, #Position2+#Length2) +1
END
PRINT(#FinalString);
But unable to get the expected result.
This is not pretty dynamic SQL, however...
USE Sandbox;
DECLARE #Str1 VARCHAR(MAX) = 'John A Mak|Street Road UAE';
DECLARE #Str2 VARCHAR(MAX) = '[First Name],[Last Name],[Middle Name]|[Address1],[Address2]';
DECLARE #WHERE nvarchar(MAX);
SET #WHERE = STUFF((SELECT N' + ' + NCHAR(10) +
STUFF((SELECT N' + ' +NCHAR(10)+
N'PATINDEX(' + QUOTENAME(DSn.Item,'''') + N',' + DSc.Item + N')' --This trusts no injection.I don't like this.
FROM dbo.DelimitedSplit8K(DS1.Item,' ') DSn
CROSS APPLY dbo.DelimitedSplit8K(DS2.Item,',') DSc
ORDER BY DSc.ItemNumber, DSn.ItemNumber
FOR XML PATH(N'')),1,4,N'')
FROM dbo.DelimitedSplit8K (#Str1,'|') DS1
CROSS APPLY dbo.DelimitedSplit8K (#Str2,'|') DS2
WHERE DS1.ItemNumber = DS2.ItemNumber
ORDER BY DS1.ItemNumber
FOR XML PATH(N'')),1,4,N'') + N' > 0'
SELECT #WHERE;
This outputs:
PATINDEX('John',[First Name]) +
PATINDEX('A',[First Name]) +
PATINDEX('Mak',[First Name]) +
PATINDEX('John',[Last Name]) +
PATINDEX('A',[Last Name]) +
PATINDEX('Mak',[Last Name]) +
PATINDEX('John',[Middle Name]) +
PATINDEX('A',[Middle Name]) +
PATINDEX('Mak',[Middle Name]) +
PATINDEX('Street',[Address1]) +
PATINDEX('Road',[Address1]) +
PATINDEX('UAE',[Address1]) +
PATINDEX('Street',[Address2]) +
PATINDEX('Road',[Address2]) +
PATINDEX('UAE',[Address2]) > 0
Note the use of DelimitedSplit8k, which you'll need on your instance to get this done.
Edit/Note: This is not injection safe. Specifically because of + DSc.Item +. The OP, in their sample data, provides already quoted strings; it is therefore assumed that the strings are properly quoted; I.e. not "[" & ColumnName & "]" (that is still open to injection, as any ] passed won't be escaped). If the columnnames are not properly quoted elsewhere, I strongly suggest removing the brackets ([]) in the passed value and using + QUOTENAME(DSc.Item) + instead.

SQL Server - Dynamic Table Name as Variable

I have been having problems trying to create tables with dynamic name. I keep getting these errors:
Msg 102, Level 15, State 1, Procedure SP_SearchTables, Line 159
Incorrect syntax near '#tablename'.
Msg 1087, Level 15, State 2, Procedure SP_SearchTables, Line 165
Must declare the table variable "#tablename".
Msg 1087, Level 15, State 2, Procedure SP_SearchTables, Line 171
Must declare the table variable "#tablename".
As you can see in the stored procedure, before this changes I had SearchTMP instead #tablename, but I don't want to give a fixed name, I want to give a dynamic name. With that in mind, I gave a name and some random numbers, but it keeps giving me the errors I showed previously, could you please help me?
I will post my stored procedure.
ALTER PROCEDURE [dbo].[SearchTables]
#SearchStr NVARCHAR(60),
#GenerateSQLOnly BIT = 0,
#SchemaNames VARCHAR(500) ='%'
AS
SET NOCOUNT ON
DECLARE #MatchFound BIT
SELECT #MatchFound = 0
DECLARE #CheckTableNames TABLE (Schemaname sysname, Tablename sysname)
DECLARE #SearchStringTbl TABLE (SearchString VARCHAR(500))
DECLARE #SQLTbl TABLE
(
Tablename SYSNAME,
WHEREClause VARCHAR(MAX),
SQLStatement VARCHAR(MAX),
Execstatus BIT
)
DECLARE #SQL VARCHAR(MAX)
DECLARE #TableParamSQL VARCHAR(MAX)
DECLARE #SchemaParamSQL VARCHAR(MAX)
DECLARE #TblSQL VARCHAR(MAX)
DECLARE #tmpTblname sysname
DECLARE #ErrMsg VARCHAR(100)
IF LTRIM(RTRIM(#SchemaNames)) =''
BEGIN
SELECT #SchemaNames = '%'
END
IF CHARINDEX(',',#SchemaNames) > 0
SELECT #SchemaParamSQL = 'SELECT ''' + REPLACE(#SchemaNames,',','''as SchemaName UNION SELECT ''') + ''''
ELSE
SELECT #SchemaParamSQL = 'SELECT ''' + #SchemaNames + ''' as SchemaName '
SELECT #TblSQL = 'SELECT SCh.NAME,T.NAME
FROM SYS.TABLES T
JOIN SYS.SCHEMAS SCh ON SCh.SCHEMA_ID = T.SCHEMA_ID
INNER JOIN [DynaForms].[dbo].[Enums_Tables] et ON (et.Id = T.NAME COLLATE Latin1_General_CI_AS) '
INSERT INTO #CheckTableNames (Schemaname, Tablename)
EXEC (#TblSQL)
IF NOT EXISTS(SELECT 1 FROM #CheckTableNames)
BEGIN
SELECT #ErrMsg = 'No tables are found in this database ' + DB_NAME() + ' for the specified filter'
PRINT #ErrMsg
RETURN
END
IF LTRIM(RTRIM(#SearchStr)) =''
BEGIN
SELECT #ErrMsg = 'Please specify the search string in #SearchStr Parameter'
PRINT #ErrMsg
RETURN
END
ELSE
BEGIN
SELECT #SearchStr = REPLACE(#SearchStr,',,,',',#DOUBLECOMMA#')
SELECT #SearchStr = REPLACE(#SearchStr,',,','#DOUBLECOMMA#')
SELECT #SearchStr = REPLACE(#SearchStr,'''','''''')
SELECT #SQL = 'SELECT ''' + REPLACE(#SearchStr,',','''as SearchString UNION SELECT ''') + ''''
INSERT INTO #SearchStringTbl (SearchString)
EXEC(#SQL)
UPDATE #SearchStringTbl
SET SearchString = REPLACE(SearchString ,'#DOUBLECOMMA#',',')
END
INSERT INTO #SQLTbl (Tablename, WHEREClause)
SELECT
QUOTENAME(SCh.name) + '.' + QUOTENAME(ST.NAME),
(SELECT '[' + SC.Name + ']' + ' LIKE ''' + REPLACE(SearchSTR.SearchString,'''','''''') + ''' OR ' + CHAR(10)
FROM SYS.columns SC
JOIN SYS.types STy ON STy.system_type_id = SC.system_type_id
AND STy.user_type_id =SC.user_type_id
CROSS JOIN #SearchStringTbl SearchSTR
WHERE STY.name IN ('varchar', 'char', 'nvarchar', 'nchar', 'text')
AND SC.object_id = ST.object_id
ORDER BY SC.name
FOR XML PATH('')
)
FROM
SYS.tables ST
JOIN
#CheckTableNames chktbls ON chktbls.Tablename = ST.name
JOIN
SYS.schemas SCh ON ST.schema_id = SCh.schema_id
AND Sch.name = chktbls.Schemaname
WHERE
ST.name <> 'SearchTMP'
GROUP BY
ST.object_id, QUOTENAME(SCh.name) + '.' + QUOTENAME(ST.NAME) ;
DECLARE #numbers VARCHAR(MAX)
SET #numbers = CONVERT(NUMERIC(12, 0), RAND() * 899999999999) + 100000000000
DECLARE #tablename VARCHAR(MAX)
SET #tablename = 'SearchTMP' + #numbers
UPDATE #SQLTbl
SET SQLStatement = N'SELECT * INTO ' + #tablename +' FROM ' + Tablename + ' WHERE ' + substring(WHEREClause,1,len(WHEREClause)-5)
DELETE FROM #SQLTbl
WHERE WHEREClause IS NULL
DECLARE #output TABLE (Id VARCHAR(50), Name VARCHAR(100))
WHILE EXISTS (SELECT 1 FROM #SQLTbl WHERE ISNULL(Execstatus ,0) = 0)
BEGIN
SELECT TOP 1 #tmpTblname = Tablename , #SQL = SQLStatement
FROM #SQLTbl
WHERE ISNULL(Execstatus ,0) = 0
IF #GenerateSQLOnly = 0
BEGIN
IF OBJECT_ID('#tablename','U') IS NOT NULL
DROP TABLE #tablename
EXEC (#SQL)
IF EXISTS(SELECT 1 FROM #tablename)
BEGIN
--SELECT parsename(#tmpTblname,1) FROM SearchTMP
SELECT #MatchFound = 1
INSERT INTO #output (Id, Name)
SELECT *
FROM [DynaForms].[dbo].[Enums_Tables]
WHERE id IN (SELECT parsename(#tmpTblname, 1) FROM #tablename)
END
END
ELSE
BEGIN
PRINT REPLICATE('-',100)
PRINT #tmpTblname
PRINT REPLICATE('-',100)
PRINT replace(#SQL,'INTO #tablename','')
END
UPDATE #SQLTbl
SET Execstatus = 1
WHERE Tablename = #tmpTblname
END
SELECT * FROM #output
--Select * from #SQLTbl
IF #MatchFound = 0
BEGIN
SELECT #ErrMsg = 'No Matches are found in this database ' + DB_NAME() + ' for the specified filter'
PRINT #ErrMsg
RETURN
END
SET NOCOUNT OFF
Edit
I changed my stored procedure to have dynamic sql but it gives me this error:
Msg 214, Level 16, State 2, Procedure sp_executesql, Line 1
Procedure expects parameter '#statement' of type 'ntext/nchar/nvarchar'.
I believe the problem is in my subquery, but I can't seen to make it work, could you please help me? The subquery is here:
DECLARE #SQLSUBQUERY VARCHAR(max);
SELECT #SQLSUBQUERY = 'SELECT * FROM [DynaForms].[dbo].[Enums_Tables] ';
SELECT #SQLSUBQUERY = #SQLSUBQUERY + 'WHERE id IN (SELECT parsename(#tmpTblname,1) FROM #tablename)';
INSERT INTO #output (Id, Name)
EXEC sp_executesql #SQLSUBQUERY
Full code here:
ALTER PROCEDURE [dbo].[SP_SearchTables]
#SearchStr NVARCHAR(60),
#GenerateSQLOnly Bit = 0,
#SchemaNames VARCHAR(500) ='%'
AS
SET NOCOUNT ON
DECLARE #MatchFound BIT
SELECT #MatchFound = 0
DECLARE #CheckTableNames TABLE (Schemaname sysname, Tablename sysname)
DECLARE #SearchStringTbl TABLE (SearchString VARCHAR(500))
DECLARE #SQLTbl TABLE (Tablename SYSNAME,
WHEREClause VARCHAR(MAX),
SQLStatement VARCHAR(MAX),
Execstatus BIT)
DECLARE #SQL VARCHAR(MAX)
DECLARE #TableParamSQL VARCHAR(MAX)
DECLARE #SchemaParamSQL VARCHAR(MAX)
DECLARE #TblSQL VARCHAR(MAX)
DECLARE #tmpTblname sysname
DECLARE #ErrMsg VARCHAR(100)
IF LTRIM(RTRIM(#SchemaNames)) =''
BEGIN
SELECT #SchemaNames = '%'
END
IF CHARINDEX(',',#SchemaNames) > 0
SELECT #SchemaParamSQL = 'SELECT ''' + REPLACE(#SchemaNames,',','''as SchemaName UNION SELECT ''') + ''''
ELSE
SELECT #SchemaParamSQL = 'SELECT ''' + #SchemaNames + ''' as SchemaName '
SELECT #TblSQL = 'SELECT SCh.NAME,T.NAME
FROM SYS.TABLES T
JOIN SYS.SCHEMAS SCh
ON SCh.SCHEMA_ID = T.SCHEMA_ID
INNER JOIN [DynaForms].[dbo].[Enums_Tables] et on
(et.Id = T.NAME COLLATE Latin1_General_CI_AS) '
INSERT INTO #CheckTableNames (Schemaname, Tablename)
EXEC(#TblSQL)
IF NOT EXISTS(SELECT 1 FROM #CheckTableNames)
BEGIN
SELECT #ErrMsg = 'No tables are found in this database ' + DB_NAME() + ' for the specified filter'
PRINT #ErrMsg
RETURN
END
IF LTRIM(RTRIM(#SearchStr)) =''
BEGIN
SELECT #ErrMsg = 'Please specify the search string in #SearchStr Parameter'
PRINT #ErrMsg
RETURN
END
ELSE
BEGIN
SELECT #SearchStr = REPLACE(#SearchStr,',,,',',#DOUBLECOMMA#')
SELECT #SearchStr = REPLACE(#SearchStr,',,','#DOUBLECOMMA#')
SELECT #SearchStr = REPLACE(#SearchStr,'''','''''')
SELECT #SQL = 'SELECT ''' + REPLACE(#SearchStr,',','''as SearchString UNION SELECT ''') + ''''
INSERT INTO #SearchStringTbl
(SearchString)
EXEC(#SQL)
UPDATE #SearchStringTbl
SET SearchString = REPLACE(SearchString ,'#DOUBLECOMMA#',',')
END
INSERT INTO #SQLTbl (Tablename, WHEREClause)
SELECT
QUOTENAME(SCh.name) + '.' + QUOTENAME(ST.NAME),
(SELECT '[' + SC.Name + ']' + ' LIKE ''' + REPLACE(SearchSTR.SearchString,'''','''''') + ''' OR ' + CHAR(10)
FROM SYS.columns SC
JOIN SYS.types STy ON STy.system_type_id = SC.system_type_id
AND STy.user_type_id =SC.user_type_id
CROSS JOIN #SearchStringTbl SearchSTR
WHERE
STY.name in ('varchar','char','nvarchar','nchar','text')
AND SC.object_id = ST.object_id
ORDER BY SC.name
FOR XML PATH('')
)
FROM SYS.tables ST
JOIN #CheckTableNames chktbls
ON chktbls.Tablename = ST.name
JOIN SYS.schemas SCh
ON ST.schema_id = SCh.schema_id
AND Sch.name = chktbls.Schemaname
WHERE ST.name <> 'SearchTMP'
GROUP BY ST.object_id, QUOTENAME(SCh.name) + '.' + QUOTENAME(ST.NAME) ;
declare #numbers varchar(MAx)
set #numbers = convert(numeric(12,0),rand() * 899999999999) + 100000000000
declare #tablename varchar(MAX)
set #tablename = 'SearchTMP' + #numbers
UPDATE #SQLTbl
SET SQLStatement = N'SELECT * INTO ' + #tablename +' FROM ' + Tablename + ' WHERE ' + substring(WHEREClause,1,len(WHEREClause)-5)
DELETE FROM #SQLTbl
WHERE WHEREClause IS NULL
DECLARE #output TABLE (Id VARCHAR(50), Name VARCHAR(100))
WHILE EXISTS (SELECT 1 FROM #SQLTbl WHERE ISNULL(Execstatus ,0) = 0)
BEGIN
SELECT TOP 1 #tmpTblname = Tablename , #SQL = SQLStatement
FROM #SQLTbl
WHERE ISNULL(Execstatus ,0) = 0
IF #GenerateSQLOnly = 0
BEGIN
DECLARE #SQLs NVARCHAR(MAX)
SELECT #SQLs = 'DROP TABLE dbo.' + QUOTENAME(#tablename) + '';
IF OBJECT_ID(''+#tablename+'','U') IS NOT NULL
EXEC sp_executesql #SQLs;
EXEC (#SQL)
--IF EXISTS(SELECT 1 FROM #tablename)
BEGIN
--SELECT parsename(#tmpTblname,1) FROM SearchTMP
SELECT #MatchFound = 1
DECLARE #SQLSUBQUERY VARCHAR(max);
SELECT #SQLSUBQUERY = 'SELECT * FROM [DynaForms].[dbo].[Enums_Tables] ';
SELECT #SQLSUBQUERY = #SQLSUBQUERY + 'WHERE id IN (SELECT parsename(#tmpTblname,1) FROM #tablename)';
INSERT INTO #output (Id, Name)
EXEC sp_executesql #SQLSUBQUERY
--Select * from [DynaForms].[dbo].[Enums_Tables] where id in (SELECT parsename(#tmpTblname,1) FROM #tablename)
END
END
ELSE
BEGIN
PRINT REPLICATE('-',100)
PRINT #tmpTblname
PRINT REPLICATE('-',100)
PRINT replace(#SQL,'INTO #tablename','')
END
UPDATE #SQLTbl
SET Execstatus = 1
WHERE Tablename = #tmpTblname
END
SELECT * FROM #output
--Select * from #SQLTbl
IF #MatchFound = 0
BEGIN
SELECT #ErrMsg = 'No Matches are found in this database ' + DB_NAME() + ' for the specified filter'
PRINT #ErrMsg
RETURN
END
SET NOCOUNT OFF
There are at least these errors:
IF OBJECT_ID('#tablename','U') IS NOT NULL
This is wrong because check for a table with the name #tablename
IF EXISTS(SELECT 1 FROM #tablename)
This produce the error you've got.
DROP TABLE does not accept variable, use dynamic sql to to your drop

merging the results of a SQL query

i am trying to merge the results of this query all data in one list. 'Union' didnt help...
any ideas ?
DECLARE #cnt INT = 0
DECLARE #SQLQuery AS NVARCHAR(500)
DECLARE #items AS VARCHAR(500)
DECLARE #stline AS VARCHAR(500)
while #cnt < 101
begin
set #items = 'LG_0' + convert(nvarchar(3),#cnt) + '_ITEMS'
set #stline = 'LG_0' + convert(nvarchar(3),#cnt) + '_01_STLINE'
if (OBJECT_ID (#items) is not null and OBJECT_ID(#stline) is not null )
set #SQLQuery = 'SELECT
ITM1.CODE, itm1.NAME, max (stl.date_) [latest date] , price as [latest price], '+ convert(nvarchar(3),#cnt) + ' as [proje kodu]
FROM ' + #items + ' ITM1 INNER JOIN ' + #stline + ' STL
ON ITM1.LOGICALREF = STL.STOCKREF
WHERE PRICE > 0
AND TRCODE = 1
AND CANCELLED = 0
AND INVOICEREF > 0
group by code, name, stl.DATE_ , price
'
exec (#SQLQuery)
set #cnt = #cnt +1
end
the result is this :
but i want them all union-ed... (sorry for the mostly code issue, i have to add here more typing)
I don't know why UNION didn't work for you, but the following should work:
DECLARE #cnt INT = 0
DECLARE #SQLQuery AS NVARCHAR(MAX) = ''
DECLARE #items AS VARCHAR(500)
DECLARE #stline AS VARCHAR(500)
while #cnt < 101
begin
set #items = 'LG_0' + convert(nvarchar(3),#cnt) + '_ITEMS'
set #stline = 'LG_0' + convert(nvarchar(3),#cnt) + '_01_STLINE'
if (OBJECT_ID (#items) is not null and OBJECT_ID(#stline) is not null )
set #SQLQuery = #SQLQuery + 'SELECT
ITM1.CODE, itm1.NAME, max (stl.date_) [latest date] , price as [latest price], '+ convert(nvarchar(3),#cnt) + ' as [proje kodu]
FROM ' + #items + ' ITM1 INNER JOIN ' + #stline + ' STL
ON ITM1.LOGICALREF = STL.STOCKREF
WHERE PRICE > 0
AND TRCODE = 1
AND CANCELLED = 0
AND INVOICEREF > 0
GROUP BY code, name, stl.DATE_ , price
UNION ALL
'
set #cnt = #cnt +1
end
-- SUBSTRING to remove last UNION ALL
SELECT #SQLQuery = SUBSTRING(#SQLQuery, 1, LEN(#SQLQuery) - 18)
-- For debugging purposes
-- PRINT #SQLQuery
exec (#SQLQuery)
I couldn't test it, but you can comment the exec, and uncomment the PRINT to see what query is being generated. It makes debugging dynamic SQL a whole lot easier.
The idea behind this code: first the UNION ALL query is being build, based on your conditions. Finally the last UNION ALL is removed, then the code can be executed.
DECLARE #cnt INT = 0
DECLARE #SQLQuery AS NVARCHAR(max)
DECLARE #items AS VARCHAR(500)
DECLARE #stline AS VARCHAR(500)
set #SQLQuery =''
while #cnt < 101
begin
set #items = 'LG_0' + convert(nvarchar(3),#cnt) + '_ITEMS'
set #stline = 'LG_0' + convert(nvarchar(3),#cnt) + '_01_STLINE'
if (OBJECT_ID (#items) is not null and OBJECT_ID(#stline) is not null )
set #SQLQuery = #SQLQuery + 'SELECT
ITM1.CODE, itm1.NAME, max (stl.date_) [latest date] , price as [latest price], '+ convert(nvarchar(3),#cnt) + ' as [proje kodu]
FROM ' + #items + ' ITM1 INNER JOIN ' + #stline + ' STL
ON ITM1.LOGICALREF = STL.STOCKREF
WHERE PRICE > 0
AND TRCODE = 1
AND CANCELLED = 0
AND INVOICEREF > 0
GROUP BY code, name, stl.DATE_ , price
UNION ALL
'
set #cnt = #cnt +1
end
-- SUBSTRING to remove last UNION ALL
--PRINT len(#SQLQuery)
set #SQLQuery = left ( #SQLQuery , len(#SQLQuery)-18)
--PRINT len(#SQLQuery)
-- print #SQLQuery
-- For debugging purposes
-- PRINT #SQLQuery
exec (#SQLQuery)

Procedure expects parameter '#statement' of type 'ntext/nchar/nvarchar'

Here is my query based sp:
DECLARE #GLOBALPATIENTACCOUNT VARCHAR(25)
DECLARE #Page_Index BIGINT
DECLARE #Page_Size BIGINT
DECLARE #practice_code VARCHAR(20)
DECLARE #dateFrom VARCHAR(20)
DECLARE #dateTo VARCHAR(20)
DECLARE #startFrom VARCHAR(20)
DECLARE #startTo VARCHAR(20)
DECLARE #Total_Record DECIMAL(34, 1)
DECLARE #Total_Pages DECIMAL(34, 1)
DECLARE #From_row BIGINT
DECLARE #To_row BIGINT
SET #GLOBALPATIENTACCOUNT = '999090999510103196'
SET #Page_Index = 1
SET #Page_Size = 30
SET #practice_code = 9090999
SET #dateFrom = '09/13/2014'
SET #dateTo = '10/13/2014'
SET #startFrom = 'null'
SET #startTo = 'null'
DECLARE #sqlstr AS varchar (max)
set #sqlstr='';
SET #sqlstr =#sqlstr +N'select CREATED_DTAE, DOCUMENT_CATEGORY_ID, DESCRIPTION, DOCUMENT_NAME, SHOW_ON_WEB, VIEW_BY_PATIENT, VIEW_DATE, NO_OF_IMAGES, DOCUMENT_STATUS_ID, DOCUMENT_STATUS_DESCRIPTION,
PATIENT_DOCUMENT_ID,ISDICOM,PATIENT_ACCOUNT,DOCUMENT_INDEX, ASSIGNED_TO,
CONTENT_START_DATE, COMMENTS,CHART_ID,LAST_NAME,FIRST_NAME, CONTENT_END_DATE,CREATED_BY,[CREATED DATE], MODIFIED_BY,MODIFIED_DATE,DELETED,SOURCE_PATH,CONFIDENTIAL,
DOC_UPLOAD_NAME,DOC_UPLOAD_STATUS,IS_MISC_DOC,BUTTON,SIGNED,SIGNED_BY,SIGNED_DATE, PRACTICE_CODE
into #temptbl
FROM
(
SELECT ISNULL(CREATED_DTAE,'''')as CREATED_DTAE , PATIENT_DOCUMENTS.DOCUMENT_CATEGORY_ID, ISNULL(UPPER(DT.DESCRIPTION),'''')as DESCRIPTION,
ISNULL(PATIENT_DOCUMENTS.DOCUMENT_NAME,'''') as DOCUMENT_NAME,
ISNULL(PATIENT_DOCUMENTS.SHOW_ON_WEB,''0'') AS SHOW_ON_WEB, ISNULL(PATIENT_DOCUMENTS.VIEW_BY_PATIENT,''0'') AS VIEW_BY_PATIENT,
ISNULL(CONVERT(VARCHAR(10),PATIENT_DOCUMENTS.VIEW_DATE,101),'''') AS VIEW_DATE, ISNULL(PATIENT_DOCUMENTS.NO_OF_IMAGES,''0'') AS NO_OF_IMAGES,
ISNULL((CONVERT(VARCHAR(12), CASE PATIENT_DOCUMENTS.DOCUMENT_STATUS_ID WHEN 0 THEN NULL ELSE PATIENT_DOCUMENTS.DOCUMENT_STATUS_ID END )),'''') AS DOCUMENT_STATUS_ID,
ISNULL(UPPER(DOCUMENTS_STATUS.DOCUMENT_STATUS_DESCRIPTION),'''') DOCUMENT_STATUS_DESCRIPTION , PATIENT_DOCUMENTS.PATIENT_DOCUMENT_ID,
ISNULL(PATIENT_DOCUMENTS.ISDICOM,''0'') ISDICOM, PATIENT_DOCUMENTS.PATIENT_ACCOUNT, ISNULL(PATIENT_DOCUMENTS.DOCUMENT_INDEX,0) DOCUMENT_INDEX, ISNULL(PATIENT_DOCUMENTS.ASSIGNED_TO,'''') ASSIGNED_TO ,
CONVERT(VARCHAR,PATIENT_DOCUMENTS.CONTENT_START_DATE,101) CONTENT_START_DATE, REPLACE (PATIENT_DOCUMENTS.COMMENTS,CHAR(10),'' '') AS COMMENTS, PATIENT.CHART_ID, UPPER(PATIENT.LAST_NAME)LAST_NAME,UPPER(PATIENT.FIRST_NAME) FIRST_NAME ,
CONVERT(VARCHAR,PATIENT_DOCUMENTS.CONTENT_END_DATE,101) CONTENT_END_DATE, ISNULL(UPPER(PATIENT_DOCUMENTS.CREATED_BY),'''') CREATED_BY,
CONVERT(VARCHAR,CREATED_DTAE,101) +'' ''+ LTRIM(SUBSTRING(CONVERT(VARCHAR,(CONVERT(DATETIME,CREATED_DTAE)),109),13,5))+'' ''+ SUBSTRING(CONVERT(VARCHAR,(CONVERT(DATETIME,CREATED_DTAE)),109),25,2) AS [CREATED DATE],
ISNULL(UPPER(PATIENT_DOCUMENTS.MODIFIED_BY),'''') MODIFIED_BY,
ISNULL(CONVERT(VARCHAR,PATIENT_DOCUMENTS.MODIFIED_DATE,101),'''') +'' ''+ LTRIM(SUBSTRING(CONVERT(VARCHAR,(CONVERT(DATETIME,PATIENT_DOCUMENTS.MODIFIED_DATE)),109),13,5))+'' ''+ SUBSTRING(CONVERT(VARCHAR,(CONVERT(DATETIME,PATIENT_DOCUMENTS.MODIFIED_DATE)),109),25 ,2) AS MODIFIED_DATE,PATIENT_DOCUMENTS.DELETED,ISNULL(PATIENT_DOCUMENTS.SOURCE_PATH,'''') SOURCE_PATH,ISNULL(PATIENT_DOCUMENTS.CONFIDENTIAL,0) CONFIDENTIAL,ISNULL(PATIENT_DOCUMENTS.DOC_UPLOAD_NAME,'''') DOC_UPLOAD_NAME,
ISNULL(PATIENT_DOCUMENTS.DOC_UPLOAD_STATUS,'''') DOC_UPLOAD_STATUS,CONVERT(BIT,''FALSE'') IS_MISC_DOC,'''' AS BUTTON,
PATIENT_DOCUMENTS.Signed SIGNED, PATIENT_DOCUMENTS.Sign_by SIGNED_BY, PATIENT_DOCUMENTS.Sign_date SIGNED_DATE,
PATIENT.PRACTICE_CODE AS PRACTICE_CODE
FROM PATIENT, PATIENT_DOCUMENTS
LEFT OUTER JOIN DOCUMENTS_STATUS ON PATIENT_DOCUMENTS.DOCUMENT_STATUS_ID = DOCUMENTS_STATUS.DOCUMENT_STATUS_ID,
DOCUMENT_CATEGORIES DT
WHERE PATIENT_DOCUMENTS.DOCUMENT_CATEGORY_ID = DT.DOCUMENT_CATEGORY_ID
AND PATIENT_DOCUMENTS.PATIENT_ACCOUNT = PATIENT.PATIENT_ACCOUNT AND PATIENT.Patient_GlobalId= ''' + #GLOBALPATIENTACCOUNT +'''
AND ISNULL(PATIENT.DELETED,0) <> 1
AND ISNULL(PATIENT_DOCUMENTS.DELETED, 0) <> 1
AND PATIENT.PRACTICE_CODE <> ''' + #practice_code + '''
AND PATIENT_DOCUMENTS.confidential <> 1 '
--print #sqlstr
IF (#dateFrom <> 'null')
BEGIN
SET #sqlstr = #sqlstr + ' and CONVERT(VARCHAR,ISNULL(PATIENT_DOCUMENTS.CREATED_DTAE,''''),101) >= CONVERT(VARCHAR,isnull( ''' + #dateFrom + ''',''''),101) and CONVERT(VARCHAR,ISNULL(PATIENT_DOCUMENTS.CREATED_DTAE,''''),101) <= CONVERT(VARCHAR,ISNULL(''' + #dateTo + ''',''''),101)'
--print #sqlstr
END
IF(#startFrom <> 'null')
BEGIN
SET #sqlstr = #sqlstr + ' CONVERT(VARCHAR,ISNULL(PATIENT_DOCUMENTS.CONTENT_START_DATE,''''),101) >= CONVERT(VARCHAR,ISNULL(''' + #startFrom + ''',''''),101) and CONVERT(VARCHAR,ISNULL(PATIENT_DOCUMENTS.CONTENT_START_DATE,''''),101) <= CONVERT(VARCHAR,isnull(''' + #startTo + ''',''''),101)'
END
SET #sqlstr = #sqlstr + 'UNION ALL
SELECT ISNULL(DOCUMENTS.CREATED_DATE,'''') AS CREATED_DTAE, CATAGORY_TYPE_ID AS DOCUMENT_CATEGORY_ID, ISNULL(DOCUMENT_CATEGORIES.DESCRIPTION,'''') DESCRIPTION,
(SELECT TOP 1 DOCUMENTS_CATEGORY_MAIN_PATH FROM DOCUMENTS_CATEGORY_MAIN WHERE DOCUMENTS_CATEGORY_MAIN_DESCRIPTION=''ATTACHMENTS'' )+''\'' +DOCUMENTS.FILE_NAME_FORPATH AS [DOCUMENT_NAME], isnull(DOCUMENTS.SHOW_ON_WEB,0) AS SHOW_ON_WEB,''0'' AS VIEW_BY_PATIENT
,ISNULL(NULL,'''') AS VIEW_DATE, ''0'' AS NO_OF_IMAGES,ISNULL(DOCUMENTS.DOCUMENT_STATUS_ID,'''') DOCUMENT_STATUS_ID,ISNULL(DOCUMENTS_STATUS.DOCUMENT_STATUS_DESCRIPTION,'''') DOCUMENT_STATUS_DESCRIPTION, DOC_ID AS PATIENT_DOCUMENT_ID,
ISNULL(NULL,''0'') AS ISDICOM, DOCUMENTS.PATIENT_ACCOUNT, ISNULL(NULL,0) AS DOCUMENT_INDEX,ISNULL(DOCUMENTS.ASSIGNED_TO,'''') ASSIGNED_TO, CONVERT(VARCHAR,DOCUMENTS.CONTENT_START_DATE,101) AS CONTENT_START_DATE,
ISNULL(DOCUMENTS.NOTES,'''') AS COMMENTS, '''' AS CHART_ID, UPPER(PM.LAST_NAME)LAST_NAME,UPPER(PM.FIRST_NAME) FIRST_NAME,
ISNULL(CONVERT(VARCHAR,DOCUMENTS.CONTENT_END_DATE,101),'''') AS CONTENT_END_DATE, ISNULL(DOCUMENTS.CREATED_BY,'''') CREATED_BY, ISNULL(DOCUMENTS.CREATED_DATE,'''') AS [CREATED DATE],
ISNULL(DOCUMENTS.MODIFIED_BY,'''') MODIFIED_BY, ISNULL(DOCUMENTS.MODIFIED_DATE,'''') MODIFIED_DATE, DOCUMENTS.DELETED, '''' AS SOURCE_PATH, ISNULL(DOCUMENTS.CONFIDENTIAL,0) CONFIDENTIAL, '''' AS DOC_UPLOAD_NAME, '''' AS DOC_UPLOAD_STATUS,
CONVERT(BIT,''TRUE'') IS_MISC_DOC,'''' AS BUTTON , DOCUMENTS.SIGNED AS SIGNED, DOCUMENTS.SIGN_BY AS SIGNED_BY, DOCUMENTS.SIGN_DATE AS SIGNED_DATE,
PM.PRACTICE_CODE AS PRACTICE_CODE
FROM PATIENT_DOCUMENTS_OTHERS DOCUMENTS
LEFT OUTER JOIN DOCUMENT_CATEGORIES ON DOCUMENTS.CATAGORY_TYPE_ID=DOCUMENT_CATEGORIES.DOCUMENT_CATEGORY_ID
INNER JOIN DOCUMENTS_CATEGORY_MAIN DCM ON DOCUMENTS.DOCUMENTS_CATEGORY_MAIN_ID =DCM.DOCUMENTS_CATEGORY_MAIN_ID
INNER JOIN PATIENT PM ON PM.PATIENT_ACCOUNT=DOCUMENTS.PATIENT_ACCOUNT
LEFT OUTER JOIN DOCUMENTS_STATUS ON DOCUMENTS_STATUS.DOCUMENT_STATUS_ID=DOCUMENTS.DOCUMENT_STATUS_ID
left outer join PATIENT_DOCUMENTS on DOCUMENTS.Doc_Id=PATIENT_DOCUMENTS.PATIENT_DOCUMENT_ID
WHERE ISNULL(DOCUMENTS.DELETED,0)<>1
AND PM.Patient_GlobalId='''+ #GLOBALPATIENTACCOUNT + ''' AND PM.PRACTICE_CODE<>''' + #practice_code + ''' and DOCUMENTS.confidential<>1'
IF(#dateFrom <> 'null')
BEGIN
SET #sqlstr = #sqlstr + 'and ISNULL(CONVERT(VARCHAR,PATIENT_DOCUMENTS.CREATED_DTAE,101),'''') >= ISNULL(CONVERT(VARCHAR,''' + #dateFrom + ''',101),'''') and ISNULL(CONVERT(VARCHAR,PATIENT_DOCUMENTS.CREATED_DTAE,101),'''')<=ISNULL(CONVERT(VARCHAR,''' + #dateTo + ''',101),'''')'
END
IF (#startFrom <> 'null')
BEGIN
SET #sqlstr = #sqlstr + 'CONVERT(VARCHAR,PATIENT_DOCUMENTS.CONTENT_START_DATE,101) >= CONVERT(VARCHAR,''' + #startFrom + ''',101) and CONVERT(VARCHAR,PATIENT_DOCUMENTS.CONTENT_START_DATE,101)<=CONVERT(VARCHAR,''' + #startTo + ''',101)'
END
SET #sqlstr = #sqlstr + ') PatDocTable order by PRACTICE_CODE,CREATED_DTAE desc '
EXECUTE sp_executesql #statement = #sqlstr
PRINT #sqlstr
It gives me error Procedure expects parameter '#statement' of type 'ntext/nchar/nvarchar',but when i change datatype #sqlstr AS nvarchar (max),error omitted,but it trancuate my query.Kindly help me to figure it out?
sp_executesql takes NVARCHAR as parameter not VARCHAR, change varchar(max) to nvarchar(max) will fix the problem.
DECLARE #sqlstr AS nvarchar (max)
Here is one of the possible solution:
Convert your #sqlstr to varchar(max) and instead of EXECUTE sp_executesql, use EXECUTE(#strsql).In this fashion you got your complete print query and it will also execute your query.Hope that it helps.
Declare variable as a nvarchar type when you are using command exec sp_executesql.Above you used varchar for #sqlstr variable.
Eg.
Declare #Sqlstr nvarchar(max)
SET #Sqlstr='...Your dynamic query...'
exec sp_executesql #Sqlstr
Note:Dont use brackets in exec command
using sp_executesql is very good option for this type of queries and it is not very friendly for sql injection.
ex:
DECLARE #sqlString nvarchar(500);
DECLARE #paramDefinition nvarchar(500);
DECLARE #sid int = 12546;
SET #sqlString = 'select * from SameTableBase S Where S.Id = #id';
SET #paramDefinition = N'#id int';
EXECUTE sp_executesql #sqlString , #paramDefinition , #id = #sid

SQL Server PRINT SELECT (Print a select query result)?

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

Resources