khoinguyen

Count, Total Even numbers

Mar 21st, 2012
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 0.73 KB | None | 0 0
  1. CREATE PROC sp_TongIn
  2.   @n int,
  3.   @count int out,
  4.   @total int out
  5. AS
  6.   DECLARE @last int
  7.   DECLARE @first int
  8.   SET @first = 2 -- so chan dau tien
  9.  
  10.   IF (@n % 2 = 0) SET @last = @n
  11.   ELSE SET @last = @n - 1
  12.  
  13.   SET @count = @last / 2
  14.  
  15.   SET @total = (@count / 2) * (@last + @first) -- e.g.: 2 4 6 8 10 => (2 + 10) + (4 + 8) = 12 * 2
  16.   IF (@count % 2 <> 0)
  17.   BEGIN
  18.     DECLARE @middle int
  19.     SET @middle = @last / 2 + ((@last % 2 + 1) % 2) -- e.g.: 10 / 2 + ((10 % 2 + 1) % 2) = 5 + 1 = 6
  20.     SET @total = @total + @middle
  21.   END
  22. GO
  23.  
  24. DECLARE @count int
  25. DECLARE @total int
  26.  
  27. EXEC sp_TongIn 10, @count out, @total out
  28. PRINT 'So luong so chan: ' + CAST(@count as VARCHAR)
  29. PRINT 'Tong so chan:' + CAST(@total as VARCHAR)
Advertisement
Add Comment
Please, Sign In to add comment