Advertisement
elena1234

IF Statements ( T-SQL )

Mar 28th, 2022 (edited)
1,234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.29 KB | None | 0 0
  1. --IF Statement - basic example
  2. DECLARE @MyInput INT = 1
  3.  
  4. IF @MyInput = 1
  5.     BEGIN
  6.         SELECT 'Hello World'
  7.     END
  8. ELSE IF @MyInput = 2
  9.     BEGIN
  10.         SELECT 'Farewell For Now!'
  11.     END
  12.  
  13.  
  14.  
  15. --IF Statement - stored procedure example
  16. CREATE OR ALTER PROCEDURE dbo.OrdersReport(@TopN INT, @OrderType INT)
  17.  
  18. AS
  19.  
  20. BEGIN
  21.  
  22.     IF @OrderType = 1
  23.         BEGIN
  24.             SELECT
  25.                 *
  26.             FROM (
  27.                 SELECT
  28.                     ProductName = B.[Name],
  29.                     LineTotalSum = SUM(A.LineTotal),
  30.                     LineTotalSumRank = DENSE_RANK() OVER(ORDER BY SUM(A.LineTotal) DESC)
  31.  
  32.                 FROM AdventureWorks2019.Sales.SalesOrderDetail A
  33.                     JOIN AdventureWorks2019.Production.Product B
  34.                         ON A.ProductID = B.ProductID
  35.  
  36.                 GROUP BY
  37.                     B.[Name]
  38.                 ) X
  39.  
  40.             WHERE LineTotalSumRank <= @TopN
  41.         END
  42.     ELSE IF @OrderType = 2
  43.         BEGIN
  44.             SELECT
  45.                 *
  46.             FROM (
  47.                 SELECT
  48.                     ProductName = B.[Name],
  49.                     LineTotalSum = SUM(A.LineTotal),
  50.                     LineTotalSumRank = DENSE_RANK() OVER(ORDER BY SUM(A.LineTotal) DESC)
  51.  
  52.                 FROM AdventureWorks2019.Purchasing.PurchaseOrderDetail A
  53.                     JOIN AdventureWorks2019.Production.Product B
  54.                         ON A.ProductID = B.ProductID
  55.  
  56.                 GROUP BY
  57.                     B.[Name]
  58.                 ) X
  59.  
  60.             WHERE LineTotalSumRank <= @TopN
  61.         END
  62. END
  63.  
  64.  
  65. --Calling the modified stored procedure
  66. EXEC dbo.OrdersReport 20,1
  67. EXEC dbo.OrdersReport 15,2
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement