Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
Currently I have started creating a procedure, which gets the parameters and should copy the contents of one table to another with certain conditions. I have copied the codes here. It compiles good. But nothing is affected.

ALTER PROCEDURE sp_ArchiveTable1(
@StartDate datetime,
@EndDate datetime,
@DateColumn VARCHAR(100),
@TableName VARCHAR(100),
@NewTableName VARCHAR(100)
)
AS
DECLARE @NextIDs TABLE(UniqueID int primary key)
 SELECT * INTO [@NewTableName] FROM [@TableName] 
WHERE [@DateColumn] >= @StartDate AND [@DateColumn] <= @EndDate
Posted
Comments
Maciej Los 13-May-13 5:53am    
What you mean: "nothing is affected"? Have you any error or something?

Please, see this article: Building Dynamic SQL In a Stored Procedure[^]
 
Share this answer
 
Comments
CHill60 13-May-13 5:57am    
Beat me to it! My +5
Maciej Los 13-May-13 5:58am    
Thank you, Chill ;)
Try this:
SQL
ALTER PROCEDURE sp_ArchiveTable1(
	@StartDate datetime,
	@EndDate datetime,
	@DateColumn VARCHAR(100),
	@TableName VARCHAR(100),
	@NewTableName VARCHAR(100)
)
AS
BEGIN
	DECLARE @NextIDs TABLE(UniqueID int primary key)
	DECLARE @statement nchar(1000) = N'SELECT * INTO '+@NewTableName+' FROM '+@TableName+' 
	WHERE '+@DateColumn+' BETWEEN '''+CONVERT(VARCHAR(100), @StartDate)+''' AND '''+CONVERT(VARCHAR(100), @EndDate)+''''
	PRINT @statement
	EXEC sys.sp_ExecuteSQL @statement
END
go

But you'll have to be careful about SQL injection[^].
See SQL Injection: What is it?[^]


--Amit
 
Share this answer
 
v3
I think you have to use exec(here your query) command for this to get executed.

Hope this helps...
 
Share this answer
 
Comments
Gokulnath007 13-May-13 5:53am    
EXEC sp_ArchiveTable1 '2008-08-21 13:22:51.280','2009-07-01 19:53:08.153','CreatedDate','EmployeeMaster','EmployeeMaster2012'

I have used like this. But nothing happens
Mohammed Hameed 14-May-13 2:50am    
You have to use exec inside the Stored procedure. Like exec(your select query).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900