2013-04-17 80 views
0

我有工資表。在這個薪水領域,我在單個列中添加了Lacks和數千個。所以我想使用select語句。在使用轉換時在sql中執行算術運算

我的查詢是

SELECT TOP(10) 'INSERT INTO jobs(Budget) VALUES('+ 
CAST(SUBSTRING(CAST(r.Budget AS VARCHAR(50)), 0, 
PATINDEX('%laks%', r.Budget))*100000 AS VARCHAR(50)) 
+ ',' +CAST(SUBSTRING(CAST(r.Budget AS VARCHAR(50)), PATINDEX('%laks%', r.Budget) + 4, 
patindex('%Thousands%', r.Budget) - PATINDEX('%laks%', r.Budget) - 4)* 1000 AS 
VARCHAR(50))+')' 
FROM dbo.requirementsdetailsfororganization r 

輸出

INSERT INTO jobs(Budget) VALUES(0,85000) 
INSERT INTO jobs(Budget) VALUES(200000,5000) 

這裏I want to add lacks and thousands,這意味着我要添加

  • 0,85000 = 85000

  • 200000,5000 = 205000

    在上述查詢中。

任何人有一個想法?

回答

0

輸出查詢在作業表中指定了一列,該列將被加載爲預算。 VALUES子句包含兩個值。這應該會導致以下錯誤:

Msg 110, Level 15, State 1, Line 1 
There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement. 

如果您將代碼更改爲此,則插入將工作。然而,它只會填充兩列數據,而不是添加值在一起:

SELECT TOP(10) 'INSERT INTO jobs(Budgetm Lacks) VALUES('+ 

CAST(SUBSTRING(CAST(r.Budget AS VARCHAR(50)), 0, PATINDEX('%laks%', r.Budget))*100000 AS VARCHAR(50)) 
     + ',' +CAST(SUBSTRING(CAST(r.Budget AS VARCHAR(50)), PATINDEX('%laks%', r.Budget) + 4 
    ,patindex('%Thousands%', r.Budget) - PATINDEX('%laks%', r.Budget) - 4)* 1000 AS 
    VARCHAR(50))+')' 
FROM dbo.requirementsdetailsfororganization r 

如果你想在兩列在總計列加在一起,那麼你可以使用此代碼:

SELECT TOP(10) 'INSERT INTO jobs(Budgetm Lacks) VALUES('+ 

CAST(SUBSTRING(CAST(r.Budget AS VARCHAR(50)), 0, PATINDEX('%laks%', r.Budget))*100000 AS VARCHAR(50)) 
     + ',' +CAST(SUBSTRING(CAST(r.Budget AS VARCHAR(50)), PATINDEX('%laks%', r.Budget) + 4 
    ,patindex('%Thousands%', r.Budget) - PATINDEX('%laks%', r.Budget) - 4)* 1000 AS 
    VARCHAR(50)) + CAST(SUBSTRING(CAST(r.Budget AS VARCHAR(50)), 0, PATINDEX('%laks%', r.Budget))*100000 AS VARCHAR(50)) 
     + ' + ' +CAST(SUBSTRING(CAST(r.Budget AS VARCHAR(50)), PATINDEX('%laks%', r.Budget) + 4 
    ,patindex('%Thousands%', r.Budget) - PATINDEX('%laks%', r.Budget) - 4)* 1000 AS 
     VARCHAR(50)) + ')' 
FROM dbo.requirementsdetailsfororganization r 

這將填充第二列和兩列的總和。如果您只是試圖用兩列總和來填充預算列,而沒有單獨的列,那麼您只需將逗號更改爲VALUES子句中的+號。

SELECT TOP(10) 'INSERT INTO jobs(Budget) VALUES('+ 

CAST(SUBSTRING(CAST(r.Budget AS VARCHAR(50)), 0, PATINDEX('%laks%', r.Budget))*100000 AS VARCHAR(50)) 
     + '+' +CAST(SUBSTRING(CAST(r.Budget AS VARCHAR(50)), PATINDEX('%laks%', r.Budget) + 4 
    ,patindex('%Thousands%', r.Budget) - PATINDEX('%laks%', r.Budget) - 4)* 1000 AS  VARCHAR(50))+')' 
FROM dbo.requirementsdetailsfororganization r 
+0

謝謝你的努力。但我編輯我的問題。我想在一列中添加兩個值。我不想顯示兩個值和+符號。 +符號我表示添加操作。 – Duk