SQL insert with if conditon

im using SQL SERVER 2008 R2 I have an LV table with structure identifier (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 LV_TEMP into the table with the same structure, but with the condition when Item> 9, then I have to split 9

what is the 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 this in SQL, I did in C # with the modulo operator (%) 9

thank you in advance

+5
source share
3 answers

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

+1
source

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

CASE :

INSERT INTO LV_TEMP
SELECT 
ID,
NAME,
Item = CASE WHEN Item > 9 THEN  Item % 9 ELSE ... END --Put your logic here
FROM ....
+2
insert into LV_TEMP
     select ID, Name, (case when Item > 9 then Item / 9 else Item end) as Item
     from LV
0

All Articles