Technical Article

Dynamic Sudoku for 3X3

,

Please use any Test database to execute this script, and if you written any better than this for the same output then please send it to me to: shivasssv@gmail.com

Use tempdb
go

if object_id(N'shivasp_sudokuRandom_3by3') is not null
begin
drop procedure shivasp_sudokuRandom_3by3
end
go

create proc shivasp_sudokuRandom_3by3 
as
begin
set nocount on;

declare @intval tinyint= cast(rand() * 4 as tinyint) 
declare @tbl table(id int identity,col1 tinyint,col2 tinyint,col3 tinyint)

insert into @tbl(col1)
select case when @intval=0 then @intval+1 else @intval end 

update @tbl set col2= case when (select col1 from @tbl where id=1)=1 then 2 when (select col1 from @tbl where id=1)=2 then 3 when (select col1 from @tbl where id=1)=3 then 1 else 1 end where id=1 and col2 is null
update @tbl set col3= case when (select col2 from @tbl where id=1)=1 then 2 when (select col2 from @tbl where id=1)=2 then 3 when (select col2 from @tbl where id=1)=3 then 1 else 1 end where id=1 and col3 is null

insert into @tbl(col1)
select case when (select col1 from @tbl where id=1)=1 then 2 when (select col1 from @tbl where id=1)=2 then 3 when (select col1 from @tbl where id=1)=3 then 1 else 1 end 

update @tbl set col2= case when (select col1 from @tbl where id=2)=1 then 2 when (select col1 from @tbl where id=2)=2 then 3 when (select col1 from @tbl where id=2)=3 then 1 else 1 end where id=2 and col2 is null
update @tbl set col3= case when (select col2 from @tbl where id=2)=1 then 2 when (select col2 from @tbl where id=2)=2 then 3 when (select col2 from @tbl where id=2)=3 then 1 else 1 end where id=2 and col3 is null

insert into @tbl(col1)
select case when (select col1 from @tbl where id=1)in(1,2) and (select col1 from @tbl where id=2)in(1,2) then 3 
when (select col1 from @tbl where id=1)in(1,3) and (select col1 from @tbl where id=2)in(1,3) then 2 
when (select col1 from @tbl where id=1)in(3,2) and (select col1 from @tbl where id=2)in(3,2) then 1 end 

update @tbl set col2=(
select case when (select col2 from @tbl where id=1)in(1,2) and (select col2 from @tbl where id=2)in(1,2) then 3 
when (select col2 from @tbl where id=1)in(1,3) and (select col2 from @tbl where id=2)in(1,3) then 2 
when (select col2 from @tbl where id=1)in(3,2) and (select col2 from @tbl where id=2)in(3,2) then 1 end) where id=3 and col2 is null 

update @tbl set col3=(
select case when (select col3 from @tbl where id=1)in(1,2) and (select col3 from @tbl where id=2)in(1,2) then 3 
when (select col3 from @tbl where id=1)in(1,3) and (select col3 from @tbl where id=2)in(1,3) then 2 
when (select col3 from @tbl where id=1)in(3,2) and (select col3 from @tbl where id=2)in(3,2) then 1 end) where id=3 and col3 is null 


select col1,col2,col3 from @tbl

set nocount off;
end
go
exec shivasp_sudokuRandom_3by3

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating