Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using sp_executesql in a stored proc 1

Status
Not open for further replies.

GacUtil

Programmer
Jan 5, 2006
10
US
I'm trying to build a stored proc that allows a user to specify a table name, and then the stored proc deletes all records from that tabel. Basically I'm trying to use sp_executesql within the proc to execute a DELETE statement as shown below. I keep receiving the error "Must declare the variable '@DeleteTable'." I'm not sure what I'm doing wrong. Any ideas? Thanks!

Code:
CREATE PROCEDURE dbo.spDeleteTEMPTables
(
	@TableName varchar(25)
)

AS
exec sp_executesql N'DELETE FROM @DeleteTable', N'@DeleteTable varchar(50)', @DeleteTable = @TableName
GO
 
hi
there no referencr to @DeleteTable
CREATE PROCEDURE dbo.spDeleteTEMPTables
(
@TableName varchar(25)
@DeleteTable varchar(50)
)


Durango122
 
maybe it doesn't like table names like that

Code:
--WORKS
DECLARE @IntVariable INT
DECLARE @SQLString NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)
SET @SQLString =     N'SELECT * FROM pubs.dbo.employee WHERE job_lvl = @level'

SET @ParmDefinition = N'@level tinyint'
SET @IntVariable = 35

EXECUTE sp_executesql @SQLString, @ParmDefinition,@level = @IntVariable



--Does not work


DECLARE @IntVariable varchar(50)

DECLARE @SQLString NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)
 
SET @SQLString = N'SELECT * FROM @level'

SET @ParmDefinition = N'@level varchar(50)'
SET @IntVariable = 'employee'

EXECUTE sp_executesql @SQLString, @ParmDefinition, @level = @IntVariable

you can always do something like this
Code:
create PROCEDURE dbo.spDeleteTEMPTables
(
    @TableName varchar(25)
)

AS
DECLARE @SQLString VARCHAR(500)
SET @SQLString = 'SELECT * FROM ' + @TableName
exec (@SQLString)


then change select to delete and run like this

spDeleteTEMPTables 'pubs..authors'

[/code]


Denis The SQL Menace
SQL blog:
Personal Blog:
 
Wow, thanks! The modified proc as recommended by SQLDenis works perfectly!
 
Sometimes is better to use Exec instead of sp_executesql?

[bomb]
 
sp_executesql is good if you want to return a couple specific results back into variables. But doing a simple exec is the probably easiest way to run arbitrary or changing code. I don't think there's really much difference though.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top