Problem: using varchar(max) in Query

Problem : using varchar(max) in Query

I am using the following sql query below :

declare @xml as xml

use [ops-20]
set @xml = (

select *
from dbo.test

for xml
path (‘R’),root(‘D’)
)

declare @cmd as varchar(max)
set @cmd =
‘C:\tofile.vbs C:\data.xml “‘
+ convert(varchar(MAX),@xml) + ‘” ‘
exec master..xp_cmdshell @cmd

where tofile.vbs is :

Dim ArgObj
Set ArgObj = WScript.Arguments
Set ObjFSO = CreateObject(“Scripting.FileSystemObject”)
Set ObjFile = ObjFSO.CreateTextFile(ArgObj(0))
ObjFile.WriteLine(ArgObj(1))
ObjFile.Close

Where Varchar() is set to 8000, the code woks perfectly.  When Varchar() is set to MAX, the query errors with:
“Msg 214, Level 16, State 201, Procedure xp_cmdshell, Line 1
Procedure expects parameter ‘command_string’ of type ‘varchar’.”

Is there a way of modifying the code to use Varchar(MAX)?


Solution:  using varchar(max) in Query

You are getting that error because master..xp_cmdshell requires/ supports @cmd input with size either Varchar(8000) or varchar(4000)..

It will not allow more thatn 8000 characters..