Help with Dynamic Query inside stored proc - SQL Server

Robb Hill
Robb Hill used Ask the Experts™
on
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

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Ryan ChongSoftware Team Lead

Commented:
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 Developer

Author

Commented:
You did...thanks...refactoring now
Robb HillSenior .Net Full Stack Developer

Author

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

Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Robb HillSenior .Net Full Stack Developer

Author

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 Lead

Commented:
can you provide sample of your xml content?
Robb HillSenior .Net Full Stack Developer

Author

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 Developer

Author

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 Lead

Commented:
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

Senior .Net Full Stack Developer
Commented:
EXEC sp_executesql @Insert,N'@fileData xml output',@fileData output;

Open in new window

Robb HillSenior .Net Full Stack Developer

Author

Commented:
My solution also worked inline..but not when called as stored proc
Robb HillSenior .Net Full Stack Developer

Author

Commented:
using sp_executesql seemed to handle this better.
Ryan ChongSoftware Team Lead

Commented:
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 Developer

Author

Commented:
yes - Thanks again!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial