sql server - How to create stored procedure for update/insert all combinations in SQL -


i have table like

col1, col2, col3, col4 ----  ----  ---- 1      0     1     sd 1      0     2     asdas 1      1     1     sd 1      1     2     ads   2      0     1     sad 2      0     2     ds 2      1     1     sad 2      1     2     sad 

this table represent possibilities have.i need update or insert row. if 1 row in above table not exist insert new row. if send -1 col1 or col2 or col3, need update/insert variants of column.

col1 accept 1 , 2.

col2 accept 0 , 1.

col3 accept 1 , 2.

for example:

col1 = -1, col2 = 1, col3 =  -1, col4 = test 

i need update/insert next columns

col1, col2, col3, col4 ----  ----  ----     1      1     1     test 1      1     2     test       2      1     1     test 2      1     2     test 

can me stored procedure?

create procedure [dbo].[mystoredprocedure] (    @col1 int,        @col2 int,    @col3 int,      @col4 uniqueidentifier ) 

you can use proc below (change column4 whatever data type prefer). used merge, it's fine here... others may prefer storing values in temp table , doing update followed insert (since merge has known issues... still though ;) ).

create procedure [dbo].[mystoredprocedure] (    @col1 int,        @col2 int,    @col3 int,      @col4 varchar(max) ) -- 3 tables contain possible values columns 1,2,3 (these should in separate lookup tables) ;with c1values (     select 1 v         union select 2 ) , c2values (     select 0 v     union select 1 ) , c3values (     select 1 v     union select 2 )  merge mytable using (     -- build permutations match input parameters     select  c1.v, c2.v, c3.v        c1values c1             cross join c2values c2             cross join c3values c3       c1.v = case when @col1 = -1 c1.v else @col1 end             , c2.v = case when @col2 = -1 c2.v else @col2 end             , c3.v = case when @col3 = -1 c3.v else @col3 end ) src (c1, c2, c3) on mytable.col1 = c1 , mytable.col2 = c2 , mytable.col3 = c3 when not matched     insert (col1, col2, col3, col4)     values (src.c1, src.c2, src.c3, @col4) when matched     update     set     mytable.col4 = @col4; go 

Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -