Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL insert with if condition

i m using SQL SERVER 2008 R2 i have table LV with stucture ID(varchar), name(varchar), and Item(int)

ID  Name Item
1   xxx  5
2   yyy  9
3   rrr  11
4   hhh  19

i want to insert into table LV_TEMP with the same structure but with condition when Item > 9 then i have to divide 9

what expected table LV_TEMP

ID   Name Item
1    xxx  5
2    yyy  9
31   rrr  9
32   rrr  2
41   hhh  9
42   hhh  9
43   hhh  1

how can i do that on SQL, i did on C# with operator modulo(%) 9

thanks you in advance

like image 374
user1958628 Avatar asked Oct 21 '22 15:10

user1958628


2 Answers

Modulo has the same syntax as in C#: http://msdn.microsoft.com/en-us/library/ms190279.aspx

You can use CASE expression to handle a condition:

INSERT INTO LV_TEMP
SELECT 
ID,
NAME,
Item = CASE WHEN Item > 9 THEN  Item % 9 ELSE ... END --Put your logic here
FROM ....
like image 173
Andrey Gordeev Avatar answered Oct 24 '22 13:10

Andrey Gordeev


Option with master..spt_values system table and APPLY() operator

IF OBJECT_ID('tempdb.dbo.#LV_TEMP') IS NOT NULL DROP TABLE dbo.#LV_TEMP
SELECT CASE WHEN t.Item > 9 THEN (t.ID * 10) + ROW_NUMBER() OVER(PARTITION BY ID ORDER BY (SELECT 1)) ELSE t.ID END AS ID,
       t.Name, 
       CASE WHEN o.Number != (t.Item / 9) THEN 9 ELSE Item % 9 END AS Item
INTO #LV_TEMP
FROM dbo.test21 t CROSS APPLY(
                              SELECT v.Number
                              FROM master..spt_values v
                              WHERE v.type = 'P' 
                                AND v.number < (CASE WHEN t.Item > 9 THEN (t.Item / 9) + 1 ELSE 1 END)
                              ) o

SELECT *
FROM #LV_TEMP  

Result:

ID  Name Item


1   xxx 5
2   yyy 9
31  rrr 9
32  rrr 2
41  hhh 9
42  hhh 9
43  hhh 1 

Demo on SQLFiddle

like image 36
Aleksandr Fedorenko Avatar answered Oct 24 '22 13:10

Aleksandr Fedorenko