Author |
Topic |
zwheeler
Starting Member
25 Posts |
Posted - 2013-08-29 : 16:37:38
|
HiI have cursor that loops through a table (the table only contains columnnames of several tables) the cursor has a variable declared@columnnamewhen i run the following it works fineselect @columnname,0,0,0,0from temp_prtit gives me my expected outputmtr_5120,0,0,0,0mtr_3247,0,0,0,0mtr_5160,0,0,0,0etc........now i want to get the min of each column name like soselect @columnname,min(mtr_5120),0,0,0from temp_prt ------> this works for min(mtr_5120)mtr_5120,34.5,0,0,0now I want to generalize so I try to pass in the variable name and Ido the followingselect @columnname,min(@columnname),0,0,0from temp_prt(the columname (@columnname) exists in the table temp_prt)but now i get an errorMsg 8114, Level 16, State 5, Line 29Error converting data type varchar to decimal.how can i pass the colunmame into the min and max functions or is that at all ppossible. I also tried the following:select @columnname,'min(' + @columnname + ')',0,0,0from temp_prtbut i get the same errorMsg 8114, Level 16, State 5, Line 29Error converting data type varchar to decimal.Any help would be greatly appreciated |
|
tkizer
Almighty SQL Goddess
38200 Posts |
|
zwheeler
Starting Member
25 Posts |
Posted - 2013-08-29 : 18:22:54
|
thank youhere is my solution--define my outer loopDECLARE @getName CURSOR, @columnname varchar(35),@sql nvarchar(2000);SET @getName = CURSOR FOR SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'temp_prt' order by column_nameOPEN @getNameFETCH NEXTFROM @getName INTO @columnnameWHILE @@FETCH_STATUS = 0BEGIN--this is my inner loopDECLARE @getMetric CURSOR, @column_name varchar(35), @metric_min decimal(12,3), @metric_max decimal(12,3), @metric_avg_mean decimal(12,3), @metric_median decimal(12,3);select @sql= N'SET @getMetric = CURSOR FOR select ' + N' + min(' + @columnname + N' ),' + N' + max(' + @columnname + N' ),' + N' + avg(' + @columnname + N' ),' + N'((SELECT MAX(' + @columnname + N') FROM (SELECT TOP 50 PERCENT ' + @columnname + ' FROM temp_prt ORDER BY ' + @columnname + N') AS BottomHalf) + (SELECT MIN(' + @columnname + ') FROM (SELECT TOP 50 PERCENT ' + @columnname + ' FROM temp_prt ORDER BY ' + @columnname + N' DESC) AS TopHalf)) / 2.0' + N' from temp_prt ' + N';OPEN @getMetric';exec sp_executesql @sql,N'@getMetric cursor output',@getMetric outputFETCH NEXTFROM @getMetric INTO @metric_min,@metric_max,@metric_avg_mean,@metric_medianWHILE @@FETCH_STATUS = 0BEGIN insert into prt_metric_test (tag_column_name,mtr_min,mtr_max,mtr_avg,mtr_median) values (@columnname,@metric_min,@metric_max,@metric_avg_mean,@metric_median)FETCH NEXTFROM @getMetric INTO @metric_min,@metric_max,@metric_avg_mean,@metric_medianENDCLOSE @getMetricDEALLOCATE @getMetric--Close my outer loopFETCH NEXTFROM @getName INTO @columnnameENDCLOSE @getNameDEALLOCATE @getNameselect * from prt_metric_test |
 |
|
|
|
|