 |
|
[SQL SEVER] สร้างคอลัมน์ผลคำนวนใน temp table โดยใช้สูตรคำนวน(string) ยังไงครับ |
|
 |
|
|
 |
 |
|
ข้อมูล
Code (SQL)
MatID Unit3 QtyPerUnit
0102001 1400 6
0102001 150 6
0102002 670 20
code
Code (SQL)
DECLARE @Formula = '(Unit3 / (QtyPerUnit / 1000) /12)'
DECLARE @TempTbl table (
MatID varchar(15),Unit3 float,QtyPerUnit Float --Result As @Formula
)
insert into @TempTbl
select S.MatID, sum(S.Unit3) as Unit3,M.QtyPerUnit from tbStock S
inner join tbMat M on S.MatID = M.MatID
inner join tbSubCategory SC on M.SubCatID = sc.SubCatID
where sc.SubCatID = 'SCID002'
group by S.MatID,M.QtyPerUnit
select *,QtyPerUnit * Unit3 As Result from @TempTbl
ผลลัพทธ์
Code (SQL)
MatID Unit3 QtyPerUnit Result
0102001 1550 6 9300
0102002 670 20 13400
ผมอยากทราบว่า ผมกำหนดสูตรคำนวนไว้ใน String แล้วจะให้มันคำนวนจากสูตรนั้นยังไงครับ
เช่นสูตรที่ผลลัพธ์แสดงตอนนี้คือ QtyPerUnit * Unit3 ผมต้องการแทนที่สูตรนี้จากตัวแปร @Formula ยังไงครับ
Tag : Ms SQL Server 2005, Ms SQL Server 2008, Ms SQL Server 2012, Ms SQL Server 2014, Ms SQL Server 2016
|
ประวัติการแก้ไข 2017-08-17 16:17:31 2017-08-17 16:18:33 2017-08-17 16:24:42
|
 |
 |
 |
 |
Date :
2017-08-14 09:43:30 |
By :
anbiun |
View :
2870 |
Reply :
4 |
|
 |
 |
 |
 |
|
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|
ได้แล้วครับ
1. สร้าง Procedure แทน Function
Code (SQL)
CREATE PROCEDURE GetDozen
-- Add the parameters for the stored procedure here
@SubCatID varchar(max),
@Formula varchar(max)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
drop table ##Temps
drop table ##TempTable
select * into ##Temps
from
(select S.MatID, sum(S.Unit3) as Unit3,M.QtyPerUnit from tbStock S
inner join tbMat M on S.MatID = M.MatID
inner join tbSubCategory SC on M.SubCatID = sc.SubCatID
where sc.SubCatID = @SubCatID
group by S.MatID,M.QtyPerUnit) data
exec ('SELECT '+ @Formula +' As RES,MatID INTO ##TempTable FROM ##Temps')
select * from ##TempTable
END
GO
เรียกใช้
Code (SQL)
exec GetDozen @SubCatID='scid002',@Formula='Unit3 * QtyPerUnit'
|
 |
 |
 |
 |
Date :
2017-08-18 09:07:21 |
By :
anbiun |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
 |
|
|
 |
 |
|

|
 |
 |
 |
 |
Date :
2017-08-20 05:33:29 |
By :
mr.win |
|
 |
 |
 |
 |
|
|
 |
 |
|
 |
 |
|
|