Help with Dynamic Query inside stored proc - SQL Server

I have the following stored proc....I am passing @FileData into the from clause....its of type xml ...but the dynamic sql is nvarchar.

how do I format this so that it will use the variable @FileData.

The sql runs fine in a test..only when called as stored proc  I get
Must declare the scalar variable "@fileData".

Here is the stored proc so far.

USE [SharePoint2007Archive]
GO
/****** Object:  StoredProcedure [dbo].[uspCreateAttachments]    Script Date: 5/9/2019 8:49:29 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[uspCreateAttachments]
@ReqID nvarchar(50),
@TableName varchar(MAX),
@xQuery VARCHAR(100),
@fileData XML
AS


BEGIN
Declare @Insert nvarchar(max);

	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET NOCOUNT ON;

set @Insert = 'INSERT INTO sharePoint2007Archive.dbo.Attachments (RequestID,Form, Document)
Select '   + QUOTENAME(@ReqID,'''') + ' as RequestID, ' + + QUOTENAME(@TableName,'''') + ' as Form, 
 xData.Col.value(''*:Document[1]'',''nvarchar(max)'') Document
from @fileData.nodes(''' + @xQuery + ''') AS xData(Col)
where DATALENGTH(xData.Col.value(''*:Document[1]'',''nvarChar(MAX)'')) > 0;'
print @Insert;

execute(@Insert);

print 'Inserted New Request ' + @ReqID + 'for Form ' +  @Tablename


END -- uspCreateAttachments

Open in new window

LVL 12
Robb HillSenior .Net Full Stack DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ryan ChongSoftware Team LeadCommented:
you can't use @fileData as part of the String in your dynamic query.

to make it easier, you got to load the content of @fileData into a temporary table and then your dynamic query can refer to it.

I think I have answered that similarly in one of your previous questions. for your consideration.
Robb HillSenior .Net Full Stack DeveloperAuthor Commented:
You did...thanks...refactoring now
Robb HillSenior .Net Full Stack DeveloperAuthor Commented:
Ryan:

Still not working...but im thinking I have to do a cross apply here...not sure how.  Please help.

Here is what I have so far.

ALTER PROCEDURE [dbo].[uspCreateAttachments]
@ReqID nvarchar(50),
@TableName varchar(MAX),
@xQuery VARCHAR(100),
@fileData XML
AS


BEGIN
Declare @Insert nvarchar(max);

	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET NOCOUNT ON;

IF OBJECT_ID('tempdb..#tmpXML') IS NOT NULL
			   DROP TABLE #xmlTmp

			   select @fileData f into #xmlTmp


set @Insert = 'INSERT INTO sharePoint2007Archive.dbo.Attachments (RequestID,Form, Document)
Select '   + QUOTENAME(@ReqID,'''') + ' as RequestID, ' + + QUOTENAME(@TableName,'''') + ' as Form, 
 xData.Col.value(''*:Document[1]'',''nvarchar(max)'') Document
from f.nodes(''' + @xQuery + ''') AS xData(Col)
where DATALENGTH(xData.Col.value(''*:Document[1]'',''nvarChar(MAX)'')) > 0;'
print @Insert;

EXECUTE @Insert


print 'Inserted New Request ' + @ReqID + 'for Form ' +  @Tablename


END -- uspCreateAttachments

Open in new window

Get Blueprints for Increased Customer Retention

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

Robb HillSenior .Net Full Stack DeveloperAuthor Commented:
another refactor....not working.

USE [SharePoint2007Archive]
GO
/****** Object:  StoredProcedure [dbo].[uspCreateAttachments]    Script Date: 5/9/2019 8:49:29 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[uspCreateAttachments]
@ReqID nvarchar(50),
@TableName varchar(MAX),
@xQuery VARCHAR(100),
@fileData XML
AS


BEGIN
Declare @Insert nvarchar(max);

	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET NOCOUNT ON;

IF OBJECT_ID('tempdb..#tmpXML') IS NOT NULL
			   DROP TABLE #xmlTmp

			   select @fileData f into #xmlTmp


set @Insert = 'INSERT INTO sharePoint2007Archive.dbo.Attachments (RequestID,Form, Document)
Select '   + QUOTENAME(@ReqID,'''') + ' as RequestID, ' + + QUOTENAME(@TableName,'''') + ' as Form, 
 xData.Col.value(''*:Document[1]'',''nvarchar(max)'') Document
FROM #xmlTmp cross apply f.nodes(''' + @xQuery + ''') AS xData(Col)
where DATALENGTH(xData.Col.value(''*:Document[1]'',''nvarChar(MAX)'')) > 0;'
print @Insert;

EXECUTE @Insert


print 'Inserted New Request ' + @ReqID + 'for Form ' +  @Tablename


END -- uspCreateAttachments

Open in new window

Ryan ChongSoftware Team LeadCommented:
can you provide sample of your xml content?
Robb HillSenior .Net Full Stack DeveloperAuthor Commented:
Yes...and this is new error as of last example.

The name 'INSERT INTO sharePoint2007Archive.dbo.Attachments (RequestID,Form, Document)
Select '1234' as RequestID, 'Test' as Form,
 xData.Col.value('*:Document[1]','nvarchar(max)') Document
FROM #xmlTmp cross apply f.nodes('/*:myFields/*:Exceptions_Sec/*:ExceptionsMain_Sec') AS xData(Col)
where DATALENGTH(xData.Col.value('*:Document[1]','nvarChar(MAX)')) > 0;' is not a valid identifier.


declare @fileData xml = '<?xml version="1.0" encoding="utf-8"?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<?mso-infoPath-file-attachment-present?>
<my:myFields xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:tns="http://tempuri.org/" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2008-07-15T21:17:40" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xml:lang="en-US">
	<my:Main>
		<my:CreateDate>2010-10-19</my:CreateDate>
		<my:RequestID>1234</my:RequestID>
		<my:QuarterEndDate>09/30/2010</my:QuarterEndDate>
		<my:PreparedBy>sanitize</my:PreparedBy>
		<my:NTUserName>sanitize</my:NTUserName>
		<my:UserEmail>sanitize</my:UserEmail>
	</my:Main>
	<my:Exceptions_Sec>
		<my:ExceptionsChoice>sanitize</my:ExceptionsChoice>
		<my:ExceptionDesc_Sec>
			<my:ViolationDescription><html xmlns="http://www.w3.org/1999/xhtml" xml:space="preserve"><div>sanitize</div></html></my:ViolationDescription>
		</my:ExceptionDesc_Sec>
		<my:ExceptionsMain_Sec>
			<my:Document>sanitize</my:Document>
		</my:ExceptionsMain_Sec>
	</my:Exceptions_Sec>
	<my:Variable>
		<my:FormStatus>Completed</my:FormStatus>
		<my:QuarterYear>2010</my:QuarterYear>
		<my:QuarterMonth>10</my:QuarterMonth>
		<my:SubmittedQuarter>2010 3rd Qtr</my:SubmittedQuarter>
		<my:CurrentLoginNTName></my:CurrentLoginNTName>
		<my:InTheList>1</my:InTheList>
		<my:DocAttached>1</my:DocAttached>
	</my:Variable>
	<my:Acknowledgement>
		<my:SignatureStatus>1</my:SignatureStatus>
		<my:SignatureSignedBy>sanitize</my:SignatureSignedBy>
		<my:SignedDate>2010-10-19</my:SignedDate>
		<my:Comments></my:Comments>
	</my:Acknowledgement>
	<my:Alert></my:Alert>
	<my:Before3rdQtr2010></my:Before3rdQtr2010>
	<my:After3rdQtr2010></my:After3rdQtr2010>
</my:myFields>'

Open in new window

Robb HillSenior .Net Full Stack DeveloperAuthor Commented:
Ryan..I got it....but thanks for getting me thinking on a different path.

here is solution.

USE [SharePoint2007Archive]
GO
/****** Object:  StoredProcedure [dbo].[uspCreateAttachments]    Script Date: 5/9/2019 8:49:29 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[uspCreateAttachments]
@ReqID nvarchar(50),
@TableName varchar(MAX),
@xQuery VARCHAR(100),
@fileData XML
AS


BEGIN
Declare @Insert nvarchar(max);

	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET NOCOUNT ON;


set @Insert = N'INSERT INTO sharePoint2007Archive.dbo.Attachments (RequestID,Form, Document)
Select '   + QUOTENAME(@ReqID,'''') + ' as RequestID, ' + + QUOTENAME(@TableName,'''') + ' as Form, 
 xData.Col.value(''*:Document[1]'',''nvarchar(max)'') Document
FROM @fileData.nodes(''' + @xQuery + ''') AS xData(Col)
where DATALENGTH(xData.Col.value(''*:Document[1]'',''nvarChar(MAX)'')) > 0;'
print @Insert;

EXEC sp_executesql @Insert,N'@fileData xml output',@fileData output;


print 'Inserted New Request ' + @ReqID + 'for Form ' +  @Tablename


END -- uspCreateAttachments

Open in new window

Ryan ChongSoftware Team LeadCommented:
this worked for me:

declare @ReqID nvarchar(50) = '100',
@TableName varchar(MAX) = 'Bla',
@xQuery VARCHAR(100) = '//test',

@fileData xml = '<?xml version="1.0" encoding="utf-8"?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<?mso-infoPath-file-attachment-present?>
<my:myFields xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:tns="http://tempuri.org/" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2008-07-15T21:17:40" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xml:lang="en-US">
	<my:Main>
		<my:CreateDate>2010-10-19</my:CreateDate>
		<my:RequestID>1234</my:RequestID>
		<my:QuarterEndDate>09/30/2010</my:QuarterEndDate>
		<my:PreparedBy>sanitize</my:PreparedBy>
		<my:NTUserName>sanitize</my:NTUserName>
		<my:UserEmail>sanitize</my:UserEmail>
	</my:Main>
	<my:Exceptions_Sec>
		<my:ExceptionsChoice>sanitize</my:ExceptionsChoice>
		<my:ExceptionDesc_Sec>
			<my:ViolationDescription><html xmlns="http://www.w3.org/1999/xhtml" xml:space="preserve"><div>sanitize</div></html></my:ViolationDescription>
		</my:ExceptionDesc_Sec>
		<my:ExceptionsMain_Sec>
			<my:Document>sanitize</my:Document>
		</my:ExceptionsMain_Sec>
	</my:Exceptions_Sec>
	<my:Variable>
		<my:FormStatus>Completed</my:FormStatus>
		<my:QuarterYear>2010</my:QuarterYear>
		<my:QuarterMonth>10</my:QuarterMonth>
		<my:SubmittedQuarter>2010 3rd Qtr</my:SubmittedQuarter>
		<my:CurrentLoginNTName></my:CurrentLoginNTName>
		<my:InTheList>1</my:InTheList>
		<my:DocAttached>1</my:DocAttached>
	</my:Variable>
	<my:Acknowledgement>
		<my:SignatureStatus>1</my:SignatureStatus>
		<my:SignatureSignedBy>sanitize</my:SignatureSignedBy>
		<my:SignedDate>2010-10-19</my:SignedDate>
		<my:Comments></my:Comments>
	</my:Acknowledgement>
	<my:Alert></my:Alert>
	<my:Before3rdQtr2010></my:Before3rdQtr2010>
	<my:After3rdQtr2010></my:After3rdQtr2010>
</my:myFields>'


Declare @Insert nvarchar(max);


IF OBJECT_ID('tempdb..#xmlTmp') IS NOT NULL
	DROP TABLE #xmlTmp

select @fileData f into #xmlTmp

select * from 
(
	select 
    xData.Col.value('*:Document[1]','nvarchar(max)') Document
	from #xmlTmp 
	CROSS APPLY
	f.nodes('/*:myFields/*:Exceptions_Sec/*:ExceptionsMain_Sec') AS xData(Col)
	where DATALENGTH(xData.Col.value('*:Document[1]','nvarChar(MAX)')) > 0	   
)  as Result

Open in new window

Robb HillSenior .Net Full Stack DeveloperAuthor Commented:
EXEC sp_executesql @Insert,N'@fileData xml output',@fileData output;

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Robb HillSenior .Net Full Stack DeveloperAuthor Commented:
My solution also worked inline..but not when called as stored proc
Robb HillSenior .Net Full Stack DeveloperAuthor Commented:
using sp_executesql seemed to handle this better.
Ryan ChongSoftware Team LeadCommented:
using sp_executesql seemed to handle this better.
you got to use that when you trying to execute something that generated from dynamic string
Robb HillSenior .Net Full Stack DeveloperAuthor Commented:
yes - Thanks again!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.