Question : Stored Procedure Loops etc

Hi All,

Im trying to create a stored procedure that loops through a table and converts date and time strings i.e. 20100801 175900 to a date time object. This date time object then wants to be inserted into another column. I have written a SP todo this but I keep getting the error "Must declare the scalar variable "@FirstID"." I dont understand why as there seems to be no problem declaring the varible. If anyone could help, or help me tidy this up it would be greatful.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
ALTER PROCEDURE [dbo].[wsp_Update_DateTime](@Table char(50),@TableID char(50), @DateField char(50), @TimeField char(50),@DateTimeField char(50))
	-- Add the parameters for the stored procedure here
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @FirstID int
	DECLARE @Date char(20)
	DECLARE @Time char(20)
	DECLARE @DT char(40)
	DECLARE @DateTime datetime

	DECLARE @cmd AS NVARCHAR(max)

	SET @cmd = N'SELECT @FirstID = Min(' + @TableID + ') FROM ' + @Table
	EXEC sp_executesql @cmd 

	WHILE @FirstID IS NOT NULL
	BEGIN

		DECLARE @cmd2 as NVARCHAR(max);

		SET @cmd2 = N'SELECT @Date = ' + @DateField + ', @Time = ' + @TimeField + ' FROM  ' + @Table + ' WHERE ' + @TableID + ' = ' + @Table;

		EXEC sp_executesql @cmd2;

		SET @DT = substring(@Date,1,4) + '-' + substring(@Date,5,2) + '-' + substring(@Date,7,2) + ' ' + substring(@Time,1,2) + ':' + substring(@Time,3,2) + ':' + substring(@Time,5,2);

		SET @DateTime = convert(datetime,@DT,20);

		DECLARE @cmd3 as NVARCHAR(max);

		SET @cmd3 = N'UPDATE ' + @Table + ' SET ' + @DateTimeField + ' = @DateTime WHERE ' + @TableID + ' = @FirstID';

		EXEC sp_executesql @cmd3; 
	
		DECLARE @cmd4 AS NVARCHAR(max)

		SET @cmd4 = N'SELECT @FirstID = Min(' + @TableID + ') FROM ' + @Table + ' WHERE ' + @TableID + ' > @FirstID';
		
		EXEC sp_executesql @cmd4 

	END

Answer : Stored Procedure Loops etc

I would start by not using Dynamic SQL where possible.  So in other words instead of passing in the table and the column have a Stored Procedure for each table.  Than your UPDATE statement can be reduced to:

UPDATE YourTableName
SET  YourDateTimeColumn = CONVERT(datetime, STUFF(STUFF(STUFF(STUFF(YourDateCharColumn, 5, 0, '-'), 8, 0, '-'), 14, 0, ':'), 17, 0, ':'), 120)
WHERE YourTableID  = @FirstID
Random Solutions  
 
programming4us programming4us