-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCheckWinner.sql
94 lines (92 loc) · 1.58 KB
/
CheckWinner.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[pCheckWinner]
as
if
-- check rows
exists (
select *
from TicTacToe
where [1]=[2] and [2]=[3]
and [1] is not null
)
or
-- check columns
-- (transpose and repeat)
exists (
select *
from
(
select row, col, cast(player as float) as player
from TicTacToe
unpivot
(
player for col in ([1],[2],[3])
) unpiv
) src
pivot
(
sum(player)
for row in ([1],[2],[3])
) piv
where [1]=[2] and [2]=[3]
)
or
-- check diagonal 1
exists (
select * from
(
select [1] as player from TicTacToe
where row = 1
union all
select [2] as player from TicTacToe
where row = 2
union all
select [3] as player from TicTacToe
where row = 3
) Temp
having avg(isnull(cast(player as float), 5.0))=0 or avg(isnull(cast(player as float), 5.0))=1
)
or
-- check diagonal 2
exists (
select * from
(
select [1] as player from TicTacToe
where row = 3
union all
select [2] as player from TicTacToe
where row = 2
union all
select [3] as player from TicTacToe
where row = 1
) Temp
having avg(isnull(cast(player as float), 5.0))=0 or avg(isnull(cast(player as float), 5.0))=1
)
begin
print 'Someone won... you know who. Game reset.'
select * from vGameBoard
update TicTacToe set [1]=null,[2]=null,[3]=null
return 1
end
else
begin
if not exists (
select *
from TicTacToe
where [1] is null
or [2] is null
or [3] is null
)
begin
-- set board when tied
print 'Tie game'
select * from vGameBoard
update TicTacToe set [1]=null,[2]=null,[3]=null
return 1
end
end
-- show game result
select * from vGameBoard