我有一个表,其中一个列值将具有公式。 获得结果的查询是什么。
| Student | Dept | col1 | col2 | col3 | col4 | col5 |
|-----------------------------------------------------------------|
| 100 | ECE | 10 | 45 | 45 | col1+col2 | 55 |
| 101 | EEE | 25 | 25 | 25 | col1*col2 | 625 |
| 102 | MECH | 45 | 50 | 50 | col1/col2 | 0.9 |
| 103 | CIVIL | 35 | 30 | 3 | (Col1/Col2)*Col3 | 3.5 |
| 104 | BIO | 45 | 90 | 90 | Col1-Col2 | -45 |
| 105 | CSE | 60 | 16 | 65 | Col1%Col2 | 12 |
我需要编写一个查询来派生col5
,并且该值应该是每条记录col4
的结果。
答案 0 :(得分:0)
declare @Student int,@Dept varchar(100),@col1 int,@col2 int,@col3 int,@col4 varchar(100)
declare @stmt nvarchar(max),@params nvarchar(max),@col5 numeric(12,2)
declare @resultset table (Student int,Dept varchar(100),col1 int,col2 int,col3 int,col4 varchar(100),col5 numeric(12,2))
declare c cursor local fast_forward for select * from t
open c
while 1=1
begin
fetch next from c into @Student ,@Dept ,@col1 ,@col2 ,@col3 ,@col4
if @@fetch_status != 0 break
set @stmt = 'select @result=' + replace(replace(replace (@col4,'Col1',@col1),'Col2',@col2),'Col3',@col3)
set @params = N'@result numeric(12,2) out'
exec sp_executesql @stmt,@params,@col5 out
insert into @resultset values (@Student ,@Dept ,@col1 ,@col2 ,@col3 ,@col4 ,@col5)
end
close c
deallocate c
select * from @resultset
答案 1 :(得分:-1)
CREATE TABLE #CalCulation(Student INT, Dept VARCHAR(100) , col1 DECIMAL(12,2), col2 DECIMAL(12,2), col3 DECIMAL(12,2), col4 VARCHAR(100), col5 DECIMAL(12,2) ,UpFlg TINYINT DEFAULT(0))
CREATE TABLE #Calc(Id INT ,Result DECIMAL(12,2))
DECLARE @Id INT,@Col1 DECIMAL(12,2),@col2 DECIMAL(12,2), @col3 DECIMAL(12,2),@col4 VARCHAR(100),@ExecQuery VARCHAR(200)
INSERT INTO #CalCulation( Student , Dept , col1 , col2 , col3 , col4 )
SELECT 100,'ECE', 10 , 45 , 45 , 'col1+col2' UNION ALL
SELECT 101,'EEE', 25 , 25 , 25 , 'col1*col2' UNION ALL
SELECT 102,'MECH', 45 , 50 , 50 , 'col1/col2' UNION ALL
SELECT 103,'CIVIL', 35 , 30 , 3 , '(Col1/Col2)*Col3' UNION ALL
SELECT 104,'BIO', 45 , 90 , 90 , 'Col1-Col2' UNION ALL
SELECT 105,'CSE', 60 , 16 , 65 , 'Col1%Col2'
WHILE EXISTS(SELECT 1 FROM #CalCulation WHERE UpFlg = 0)
BEGIN
SELECT Top 1 @Id = Student, @col1 = col1 , @col2 = col2, @col3 = col3,@col4 = col4 FROM #CalCulation WHERE UpFlg = 0
SET @ExecQuery = 'SELECT '+ CAST(@Id AS VARCHAR) +' ,SUM (' + REPLACE(REPLACE(REPLACE (@col4,'Col1',@col1),'Col2',@col2),'Col3',@col3) +')'
INSERT INTO #Calc (Id ,Result)
EXEC (@ExecQuery)
UPDATE #CalCulation SET UpFlg = 1 WHERE Student = @Id
END
UPDATE #CalCulation SET col5 = Result
FROM #Calc WHERE Id = Student
SELECT * FROM #CalCulation