Wednesday, March 7, 2012

Execute script from Stored Procedure

I've been scouring the internet for hours looking for ways to execute a sql script file from within a stored procedure. I found a way to do it with the following t-sql code:

select @.cmd = 'sqlcmd -S SASHA2400\Erato -U cop -P xxxx -ic:\' + @.Filename + '.sql'

exec master..xp_cmdshell @.cmd

But, I'm worried about security risks with using xp_cmdshell. I would think there's be an easier way to do this. I'm also getting the following error when executing the stored proc:

EXECUTE permission denied on object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.

My original issue was trying to create a dynamic view (which is being built by code) in the database and it was limiting the number of characters to 8000 b/c I had the sql statement defined as a varchar. So, what I decided to do was to write the 'create view' statement to a .sql file and try to create it on the server (so I don't have to rely on the varchar limitations). Does anyone have any ideas on any other ways to get around this?

Please help!
Thank You!
sasha@.wddincdotcom

I'm using 2005 beta.

It partially works. What I mean by that is, if I declare the @.sql parameter as varchar(max) in the stored procedure and I directly execute it in query analyzer then all is fine. But, I'm executing it in VB 6 with an rdopreparedstatment and for some reason, the @.sql parameter is not getting passed. All the other parameters are passed and when i step through the debug code, it is all there. BUT, when I set a watch on the preparedstatement the SQL parameter has a size of 0. Is this what is preventing the string from being passed?

Thanks,
Sasha|||VB6 / older ODBC or ADO will not understand the new data types. That might be the problem. But you can just use text/ntext and pass the value from VB directly. This should work fine.|||That worked! Thank YOU!!|||Generally speaking, you should avoid doing these type of operations on the server. It has lot of issues like security, management, performance, maintanability and complexity. Xp_cmdshell has it's own risks also like you are already aware of. You have to grant execute permission to the desired users/groups/roles on the XP for this to work. The default settings in SQL Server 2005 is different from older versions. You can still do what you want using dynamic SQL by doing one of the following:

1. Use varchar(MAX) or nvarchar(MAX) data types for the variables in SQL Server 2005. These have about 2GB limit so should suffice to build long strings
2. Use multiple varchar(8000) variables in older versions of SQL Server and concatenate them together & execute via EXECUTE statement (exec(@.v1 + @.v2 + @.v3))

No comments:

Post a Comment