I have a SQL Server 2008 with a table that acts like a hash-map. basically, there's three columns (id, key, val) and I need to pull the other columns a, b, c, d, e.
The purpose is to basically choose the database I need to query data from. Similar to this issue Using the correct database
I have got the SQL using a brute force method. I'm just trying do this in a better, more efficient way
Here's the SQL I'm trying to get to work:
CREATE PROCEDURE [dbo].[me]
#partitionName VARCHAR(64),
#id INT
AS
BEGIN
SET NOCOUNT ON
SET ROWCOUNT 0
DECLARE #table as varchar(128)
DECLARE #sql as nvarchar(4000)
DECLARE #params as nvarchar(4000)
DECLARE #s_key as varchar(64)
DECLARE #paramDefinition as nvarchar(4000)
DECLARE #a INT
DECLARE #b VARCHAR(32)
DECLARE #c VARCHAR(32)
DECLARE #d VARCHAR(32)
DECLARE #e VARCHAR(32)
SET #table = #partitionName + '.dbo.hash_table'
SET #sql =
N'SELECT ' +
N' #a = MAX(CASE WHEN [key] = ''a'' THEN value ELSE '''' END),
#b = MAX(CASE WHEN [key] = ''b'' THEN value ELSE '''' END),
#c = MAX(CASE WHEN [key] = ''c'' THEN value ELSE '''' END),
#d = MAX(CASE WHEN [key] = ''d'' THEN value ELSE '''' END),
#e = MAX(CASE WHEN [key] = ''e'' THEN value ELSE '''' END)
FROM ' + #table +
N'WHERE id = ' + CONVERT(VARCHAR(3), #id)
EXEC sp_executesql #sql
But, this gives the following error
Must declare the scalar variable "#a"
I have a feeling I need to do something like pass in #paramsDefinition to sp_executesql
But so far, these have failed
SET #paramDefinition = '#a INT OUTPUT, '
+ ' #b varchar(32) OUTPUT, '
+ ' #c varchar(32) OUTPUT, '
+ ' #d varchar(32) OUTPUT,'
+ ' #r varchar(32) OUTPUT'
...
EXEC sp_executesql #sql, #paramDefintions
I get
Incorrect syntax near '='.
Here is the brute force method (which works but hits the DB 5 times)
SET #key = 'a'
SET #sql =
N' SELECT #a = val FROM ' + #table +
N' WHERE key = ' + quotename(#key, '''') +
N' AND id = ' + CONVERT(VARCHAR(3), #nid)
EXEC sp_executesql #sql, N'#a varchar(32) OUTPUT', #a = #a OUTPUT
SET #key = 'b'
SET #sql =
N' SELECT #b = val FROM ' + #table +
N' WHERE key = ' + quotename(#key, '''') +
N' AND id = ' + CONVERT(VARCHAR(3), #id)
EXEC sp_executesql #sql, N'#b varchar(32) OUTPUT', #b = #b OUTPUT
SET #key = 'c'
SET #sql =
N' SELECT #c = val FROM ' + #table +
N' WHERE key = ' + quotename(#key, '''') +
N' AND id = ' + CONVERT(VARCHAR(3), #id)
EXEC sp_executesql #sql, N'#c varchar(32) OUTPUT', #c = #c OUTPUT
SET #key = 'd'
SET #sql =
N' SELECT #d = val FROM ' + #table +
N' WHERE key = ' + quotename(#key, '''') +
N' AND id = ' + CONVERT(VARCHAR(3), #id)
EXEC sp_executesql #sql, N'#d varchar(32) OUTPUT', #d = #d OUTPUT
SET #key = 'e'
SET #sql =
N' SELECT #e = val FROM ' + #table +
N' WHERE key = ' + quotename(#key, '''') +
N' AND id = ' + CONVERT(VARCHAR(3), #id)
EXEC sp_executesql #sql, N'#e varchar(32) OUTPUT', #e = #e OUTPUT
SELECT #a as [a], #b as [b], #c as [c], #d as [d], #r as [r]
You can try to use a temporary table like this:
CREATE PROCEDURE [dbo].[me]
#partitionName VARCHAR(64),
#id INT
AS
BEGIN
SET NOCOUNT ON
SET ROWCOUNT 0
DECLARE #table as varchar(128)
DECLARE #sql as nvarchar(4000)
DECLARE #params as nvarchar(4000)
DECLARE #s_key as varchar(64)
DECLARE #paramDefinition as nvarchar(4000)
DECLARE #a INT
DECLARE #b VARCHAR(32)
DECLARE #c VARCHAR(32)
DECLARE #d VARCHAR(32)
DECLARE #e VARCHAR(32)
SET #table = #partitionName + '.dbo.hash_table'
CREATE TABLE #tmp (code varchar(50))
SET #sql =
N'SELECT ' +
N' MAX(CASE WHEN [key] = ''a'' THEN value ELSE '''' END) as [a],
MAX(CASE WHEN [key] = ''b'' THEN value ELSE '''' END) as [b],
MAX(CASE WHEN [key] = ''c'' THEN value ELSE '''' END) as [c],
MAX(CASE WHEN [key] = ''d'' THEN value ELSE '''' END) as [d],
MAX(CASE WHEN [key] = ''e'' THEN value ELSE '''' END) as [e]
FROM ' + #table +
N'WHERE id = ' + CONVERT(VARCHAR(3), #id)
INSERT INTO #tmp (code)
EXEC sp_executesql #sql
SELECT * from #tmp
Hope it helps.
Try this.....
Dynamic SQL has its own scope, Variables in your stored procedure arent visible to to your dynamic sql, you will need to declare these variables as second parameter to sp_execuetsql and since you are reverting values back in these variables, you will need to use key word OUTPUT with these variables when passing them to sp_executesql , as follows
CREATE PROCEDURE [dbo].[me]
#partitionName SYSNAME,
#id INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #table as varchar(128)
DECLARE #sql as nvarchar(4000)
DECLARE #params as nvarchar(4000)
DECLARE #s_key as varchar(64)
DECLARE #paramDefinition as nvarchar(4000)
DECLARE #a INT
DECLARE #b VARCHAR(32)
DECLARE #c VARCHAR(32)
DECLARE #d VARCHAR(32)
DECLARE #e VARCHAR(32)
SET #table = #partitionName + 'hash_table'
SET #sql = N'SELECT ' +
N' #a = MAX(CASE WHEN [key] = ''a'' THEN value ELSE '''' END),
#b = MAX(CASE WHEN [key] = ''b'' THEN value ELSE '''' END),
#c = MAX(CASE WHEN [key] = ''c'' THEN value ELSE '''' END),
#d = MAX(CASE WHEN [key] = ''d'' THEN value ELSE '''' END),
#e = MAX(CASE WHEN [key] = ''e'' THEN value ELSE '''' END)
FROM dbo.' + QUOTENAME(#table) +
N' WHERE id = #id)'
EXEC sp_executesql #sql
,N'#a INT OUTPUT, #b VARCHAR(32) OUTPUT,#b VARCHAR(32) OUTPUT,#c VARCHAR(32) OUTPUT,
#d VARCHAR(32) OUTPUT,#e VARCHAR(32) OUTPUT, #id INT'
,#a OUTPUT
,#b OUTPUT
,#c OUTPUT
,#d OUTPUT
,#e OUTPUT
,#id
END
Related
I broke this query down to the most basic. I need to add an OR statement dynamically, which includes a variable. I need to get any id and its corresponding id with an underscore. So, my resulting #SQL to execute would be:
create table #Test (OrganizationId varchar(100), OrigID varchar(50))
insert into #Test(OrganizationId,OrigID)
Values ('5','31'),
('5','31_00000'),
('5','33'),
('5','33_00000'),
('5','25'),
('5','25_00000'),
('5','HD_00000'),
('5','HD')
--
DECLARE
#OrganizationId int = 5,
#OriginId nvarchar(256) = N'31,25,33'
create table #inVars(id int NOT NULL IDENTITY PRIMARY KEY, origins varchar(256))
insert into #inVars(origins)
Values ('31'),
('33'),
('25')
DECLARE #SQL NVARCHAR(MAX),
#ParamDefinition NVARCHAR(MAX)
SET #ParamDefinition = N'#OrganizationId int,
#OriginId nvarchar(256)'
SET #SQL= 'SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId'
IF ISNULL(#OriginId,'') <> ''
SET #SQL = #SQL + ' AND OrigID in (''' + #OriginId + ''') '
DECLARE #counter INT = 1, #max INT = 0, #Origin nvarchar(50), #SQL_2 nvarchar(max)
SELECT #max = COUNT(id) FROM #inVars
WHILE #counter <= #max
BEGIN
SET #Origin = '_%'
SET #Origin = (select origins from #invars where id = CAST(#counter as varchar(10))) + #Origin
SET #SQL_2 = N' OR OrigID LIKE ''' + #Origin + ''' '
SET #SQL_2 = #SQL + #SQL_2
print(#SQL_2)
SET #counter = #counter + 1
END
EXEC sp_executesql #SQL_2,#ParamDefinition,#OrganizationId,#OriginId
drop table #inVars
drop table #Test
Here is how my query is executing now:
SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId AND OrigID in ('31,25,33') OR OrigID LIKE '31_%'
SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId AND OrigID in ('31,25,33') OR OrigID LIKE '33_%'
SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId AND OrigID in ('31,25,33') OR OrigID LIKE '25_%'
This is my desired result:
SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId AND OrigID in ('31,25,33') OR OrigID LIKE '31_%'
OR OrigID LIKE '33_%'
OR OrigID LIKE '25_%'
A few problems: You can't concatenate a NULL with a string EVER; the result is always NULL (please look at the IF #Origin IS NOT NULL line). In your loop, you should be updating #SQL, not #SQL_2. Lastly, you should wrap ORs in parens so the logic is always explicit.
SET NOCOUNT ON
create table #Test (OrganizationId varchar(100), OrigID varchar(50))
insert into #Test(OrganizationId,OrigID)
Values ('5','31'),
('5','31_00000'),
('5','33'),
('5','33_00000'),
('5','25'),
('5','25_00000'),
('5','HD_00000'),
('5','HD')
DECLARE
#OrganizationId int = 5,
#OriginId nvarchar(256) = N'31,25,33'
create table #inVars(id int NOT NULL IDENTITY PRIMARY KEY, origins varchar(256))
insert into #inVars(origins)
Values ('31'),
('33'),
('25')
DECLARE #SQL NVARCHAR(MAX),
#ParamDefinition NVARCHAR(MAX)
SET #ParamDefinition = N'#OrganizationId int,
#OriginId nvarchar(256)'
SET #SQL= 'SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId'
IF ISNULL(#OriginId,'') <> ''
SET #SQL = #SQL + ' AND (OrigID in (''' + #OriginId + ''') '
DECLARE #counter INT = 1, #max INT = 0, #Origin nvarchar(50), #SQL_2 nvarchar(max)
SELECT #max = COUNT(id) FROM #inVars
WHILE #counter <= #max
BEGIN
SET #Origin = '_%'
SET #Origin = (select origins from #invars where id = CAST(#counter as varchar(10))) + #Origin
IF #Origin IS NOT NULL
BEGIN
SET #SQL_2 = N' OR OrigID LIKE ''' + #Origin + ''' '
SET #SQL = #SQL + #SQL_2
END
SET #counter = #counter + 1
END
SET #SQL=#SQL+')'
print #SQL
drop table #inVars
drop table #Test
It is not very clear what you want here but I think you are making it harder on yourself than you need to. There is no need to use the IN because you are also finding all values that begin with the same value. And you have hard coded the same values into your temp table. Using a string splitter this is about a million times less complicated. Just split your #OriginID on the commas and use LIKE in the join.
I am using the DelimitedSplit8k which you can find here
I am pretty sure this should get you the information you are looking for. I would recommend avoiding loops whenever possible.
create table #Test (OrganizationId varchar(100), OrigID varchar(50))
insert into #Test(OrganizationId,OrigID)
Values ('5','31'),
('5','31_00000'),
('5','33'),
('5','33_00000'),
('5','25'),
('5','25_00000'),
('5','HD_00000'),
('5','HD')
DECLARE
#OrganizationId int = 5,
#OriginId nvarchar(256) = N'31,25,33'
select *
from #Test t
join DelimitedSplit8K(#OriginID, ',') x on t.OrigID like x.Item + '%'
drop table #Test
I solved this.Thanks all who replied.
create table #Test (OrganizationId varchar(100), OrigID varchar(50))
insert into #Test(OrganizationId,OrigID)
Values ('5','31'),
('5','31_00000'),
('5','33'),
('5','33_00000'),
('5','25'),
('5','25_00000'),
('5','HD_00000'),
('5','HD')
DECLARE
#OrganizationId int = 5,
#OriginId nvarchar(256) = N'31,25,33'
create table #inVars(id int NOT NULL IDENTITY PRIMARY KEY, origins varchar(256))
insert into #inVars(origins)
Values ('31'),
('33'),
('25')
DECLARE #SQL NVARCHAR(MAX),
#ParamDefinition NVARCHAR(MAX)
SET #ParamDefinition = N'#OrganizationId int,
#OriginId nvarchar(256)'
SET #SQL= 'SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId'
IF ISNULL(#OriginId,'') <> ''
BEGIN
SET #SQL = #SQL +' AND (OrigID in (''' + #OriginId + ''')) '
END
IF ISNULL(#OriginId,'') <> ''
DECLARE #counter INT = 1, #max INT = 0, #Origin nvarchar(50), #SQL_2 nvarchar(max)
SELECT #max = COUNT(id) FROM #inVars
WHILE #counter <= #max
BEGIN
SET #Origin = (select origins from #invars where id = CAST(#counter as varchar(10)))
SET #Origin = #Origin+'_%'
SET #SQL_2 = N' OR (OrigID LIKE ''' + #Origin + ''') '
SET #SQL = #SQL + #SQL_2
SET #counter = #counter + 1
END
print(#SQL)
EXEC sp_executesql #SQL,#ParamDefinition,#OrganizationId,#OriginId
drop table #inVars
drop table #Test
I'm trying to write a stored procedure in SQL Server that gets the columns as parameters. The user will select the column name from a combo box and will write the searched value for that column on a textbox.
I've been searching how to do this and so far i have this:
ALTER PROCEDURE [dbo].[SP_Select_TBL_Folio]
#cant int,
#Column1 nvarchar(50),
#Value1 nvarchar(50),
#Column2 nvarchar(50),
#Value2 nvarchar(50),
#Column3 nvarchar(50),
#Value3 nvarchar(50)
AS
BEGIN
declare #query nvarchar (max)
SET NOCOUNT ON;
if #cant = 1
BEGIN
set #query = 'SELECT * FROM TBL_Folio WHERE ' + #Column1 + ' LIKE '+ #Value1 + ' ORDER BY 1 DESC';
exec sp_executesql #query, N' '
END
else
BEGIN
if #cant = 2
BEGIN
set #query = 'SELECT * FROM TBL_Folio WHERE ' + #Column1 + ' LIKE '+ #Value1 + ' AND ' + #Column2 + ' LIKE '+ #Value2 + ' ORDER BY 1 DESC';
exec sp_executesql #query, N' '
END
ELSE
if #cant = 3
BEGIN
set #query = 'SELECT * FROM TBL_Folio WHERE ' + #Column1 + ' LIKE '+ #Value1 + ' AND ' + #Column2 + ' LIKE '+ #Value2 + ' AND ' + #Column3 + ' LIKE '+ #Value3 + ' ORDER BY 1 DESC';
exec sp_executesql #query, N' '
END
END
END
The user can send 1 to 3 values, for that I have the parameter #cant, this code works but I want to know if there is a better way to do this or how can I improve this stored procedure.
I think what you have is fine if you need to do it in an SP rather than client side. I would probabably initialize the query to the 'select * from TBL_Folio" and then append the LIKES after each if. I would also caution against using SELECT * so your client side doesn't blow up if a field gets added to the table.
If you have a need to check a variable number of fields rather than just up to 3, you can do a table-valued parameter and build up your query by looping through. Here is an example:
ALTER PROCEDURE [dbo].[GetFilteredInvoices]
#FilterColumns ColumnValueType READONLY
AS
BEGIN
SET NOCOUNT ON;
declare #columnName varchar(50), #columnValue varchar(MAX), #query nvarchar(MAX), #count int
set #query='SELECT InvoiceNumber, InvoiceDate, Customer from Invoices '
set #count=0
set #columnName=''
while exists(select * from #FilterColumns where ColumnName>#ColumnName)
begin
set #columnName=(select min(ColumnName) from #FilterColumns where ColumnName>#columnName)
if #count=0
set #query=#query+'WHERE '
else
set #query=#query+'AND '
set #query=#query+ (select ColumnName+' Like ''%'+ColumnValue+'%'' ' from #filterColumns where ColumnName=#columnName)
set #count=#count+1
end
exec sp_executesql #query
END
Here is the table valued type I used:
CREATE TYPE [dbo].[ColumnValueType] AS TABLE(
[ColumnName] [varchar](50) NULL,
[ColumnValue] [varchar](max) NULL
)
GO
Now this will take any number of columns and values to apply the filter.
Here is an example call to the procedure:
DECLARE #RC int
DECLARE #FilterColumns [dbo].[ColumnValueType]
insert into #filterColumns
Values('InvoiceNumber','345')
,('Customer','67')
EXECUTE #RC = [dbo].[GetFilteredInvoices]
#FilterColumns
I think you can perhaps improve the way that you handle your input parameters by getting rid of the #cant parameter. You can also improve the way that you build up the conditions, at the moment you are not handling the situations where only #Column2 and #Value2 or only #Column3 and #Value3 is set (perhaps it is not needed in your case, but it is still good practice to handle these types of scenarios)
CREATE PROCEDURE SP_Select_TBL_Folio
#Column1 NVARCHAR(50) = NULL,
#Value1 NVARCHAR(50) = NULL,
#Column2 NVARCHAR(50) = NULL,
#Value2 NVARCHAR(50) = NULL,
#Column3 NVARCHAR(50) = NULL,
#Value3 NVARCHAR(50) = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE
#P1 NVARCHAR(500),
#P2 NVARCHAR(500),
#P3 NVARCHAR(500),
#SQL NVARCHAR(MAX)
IF (#Column1 IS NULL OR #Column1 = '') AND (#Value1 IS NULL OR #Value1 = '')
BEGIN
-- This will build up dynamic SQL to always select records even if #Column1
-- and #Value1 is not set. This obvisously all depends on your requirements
-- and if you still need to select records if the parameters are not set, otherwise
-- it can be changed to ' WHERE ThePrimaryKeyColumn = 0'
SET #P1 = ' WHERE ThePrimaryKeyColumn > 0'
END
ELSE
BEGIN
SET #P1 = 'WHERE ' + #Column1 + ' LIKE ' + '''' + #Value1 + ''''
END
IF (#Column2 IS NULL OR #Column2 = '') AND (#Value2 IS NULL OR #Value2 = '')
BEGIN
SET #P2 = ''
END
ELSE
BEGIN
SET #P2 = ' AND ' + #Column2 + ' LIKE ' + '''' + #Value2 + ''''
END
IF (#Column3 IS NULL OR #Column3 = '') AND (#Value3 IS NULL OR #Value3 = '')
BEGIN
SET #P3 = ''
END
ELSE
BEGIN
SET #P3 = ' AND ' + #Column3 + ' LIKE ' + '''' + #Value3 + ''''
END
SET #SQL = 'SELECT * FROM TBL_Folio
[P1]
[P2]
[P3]'
-- Here we set all the conditions
SET #SQL = REPLACE(#SQL, '[P1]', #P1);
SET #SQL = REPLACE(#SQL, '[P2]', #P2);
SET #SQL = REPLACE(#SQL, '[P3]', #P3);
-- This will be replaced by EXEC(#SQL)
PRINT #SQL
END
So now you can for instance execute
EXEC SP_Select_TBL_Folio
which will give you
SELECT * FROM TBL_Folio
WHERE ThePrimaryKeyColumn > 0
or you can execute
EXEC SP_Select_TBL_Folio 'Column1','Value1'
which will give you
SELECT * FROM TBL_Folio
WHERE Column1 LIKE 'Value1'
or you can execute
EXEC SP_Select_TBL_Folio NULL,NULL,'Column2','Value2'
which will give you
SELECT * FROM TBL_Folio
WHERE ThePrimaryKeyColumn > 0
AND Column2 LIKE 'Value2'
I'm not going to list all the permutations, I'm sure you get my point.
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
I was trying to execute one of my Stored procedure but i am getting an syntax error and i am unable to understand why.
here is the sproc:
ALTER PROCEDURE [dbo].[HotlinePlusAdministration_ArticleMigrator]
#ArticleKey AS INT,
--#CategoryID AS INT,
--#Title AS Varchar(200),
--#ArticleDate AS datetime,
#DestLinkServer AS VARCHAR(50),
#UserID AS VARCHAR(8),
#ReturnMsg AS VARCHAR(1000) OUTPUT
AS
BEGIN
DECLARE #Query AS NVARCHAR(4000)
DECLARE #Log AS VARCHAR(8000)
DECLARE #ArticleID as int
DECLARE #NewArticleID as int
DECLARE #ArticleKeyExists as int
DECLARE #Title as varchar(200)
DECLARE #CategoryID as INT
DECLARE #ArticleDate as varchar(30)
DECLARE #ParmDefinition nvarchar(500);
SET XACT_ABORT ON -- Required for nested transaction
BEGIN TRAN
-- Check if ArticleID exists in Destination Server
SET #Query = N' SELECT #ArticleKeyExists = COUNT(*)
FROM ' + #DestLinkServer + '.HL2_61.dbo.Article' + ' where ArticleKey = ' + str(#ArticleKey)
SET #ParmDefinition = N'#ArticleKey int, #ArticleKeyExists int OUTPUT';
EXECUTE sp_executesql #Query , #ParmDefinition, #ArticleKey , #ArticleKeyExists OUTPUT;
IF ##ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
SET #ReturnMsg = #Log + '<span style="color:red;">ERROR: <br></span>'
RETURN -1
END
--Delete existing Articles for select page
set #Query = 'DELETE FROM ' + #DestLinkServer +
'.HL2_61.dbo.Article ' +
'WHERE ArticleKey = ' + CONVERT(VARCHAR, #ArticleKey)
--'WHERE CategoryID = ' + CONVERT(VARCHAR, #CategoryID) + ' and Title = ''' + #Title + ''' and ArticleDate = ''' + #ArticleDate + ''''
Print #Query
EXEC(#Query)
when i am trying to execute it i am getting an error here:
SELECT #ArticleKeyExists = COUNT(*)
FROM BRWSQLDC.HL2_61.dbo.Article where ArticleKey = 1591276581
Can some body please help me on this,
Thanks.
SET #ArticleKeyExists = (SELECT COUNT(*) FROM BRWSQLDC.HL2_61.dbo.Article where ArticleKey = 1591276581)
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