Other RIGHT SQL function


1. Usage of RIGHT function

SQL Server Query 1

            
 WITH CustomerPhoneSuffix AS (  
SELECT
CustomerID,
CompanyName,
Phone,
-- Extract the last 4 digits of the phone number
RIGHT(Phone, 4) AS LastFourDigits
FROM
Customers
WHERE
LEN(Phone) >= 4
),
CustomerWithFaxSuffix AS (
SELECT
CustomerID,
CompanyName,
Fax,
-- Extract the last 3 digits of the fax number if it exists
CASE
WHEN Fax IS NOT NULL AND LEN(Fax) >= 3 THEN RIGHT(Fax, 3)
ELSE NULL
END AS LastThreeFaxDigits
FROM
Customers
),
OrderDetailsWithUnitPriceSuffix AS (
SELECT
od.OrderID,
p.ProductName,
od.UnitPrice,
-- Extract the last digit of the UnitPrice
RIGHT(CAST(FLOOR(od.UnitPrice) AS VARCHAR), 1) AS UnitPriceLastDigit
FROM
[Order Details] od
JOIN
Products p ON od.ProductID = p.ProductID
)
SELECT
c.CustomerID,
c.CompanyName,
cps.LastFourDigits AS PhoneLastFour,
cfx.LastThreeFaxDigits AS FaxLastThree,
oud.OrderID,
oud.ProductName,
oud.UnitPrice,
oud.UnitPriceLastDigit
FROM
Customers c
LEFT JOIN
CustomerPhoneSuffix cps ON c.CustomerID = cps.CustomerID
LEFT JOIN
CustomerWithFaxSuffix cfx ON c.CustomerID = cfx.CustomerID
LEFT JOIN
OrderDetailsWithUnitPriceSuffix oud ON c.CustomerID = SUBSTRING(CAST(oud.OrderID AS VARCHAR), 1, 5) -- Attempting a join based on partial OrderID (illustrative, might not be logically sound)
WHERE
cps.LastFourDigits IS NOT NULL OR cfx.LastThreeFaxDigits IS NOT NULL OR oud.UnitPriceLastDigit IS NOT NULL
ORDER BY
c.CustomerID;

Create SQL query with SqlQueryBuilder 1

            
 var (sql1, parameters1) = new SqlQueryBuilder()  
.WithCTETable(new Table("CustomerPhoneSuffix"), new SqlQueryBuilder()
.Select()
.Columns("CustomerID", "CompanyName", "Phone")
.Column(new RIGHT(new Column("Phone"), 4), "LastFourDigits")
.From("Customers")
.Where(new Where(new LEN(new Column("Phone")).GreaterThanOrEqualeTo(4)))
)
.WithCTETable(new Table("CustomerWithFaxSuffix"), new SqlQueryBuilder()
.Select()
.Columns("CustomerID", "CompanyName", "Fax")
.Column(new CASE()
.When(new IS_NOT_NULL(new Column("Fax")).AND(new LEN(new Column("Fax")).GreaterThanOrEqualeTo(3)))
.Then(new RIGHT(new Column("Fax"), 3))
.Else(new Column().SetNull())
, "LastThreeFaxDigits")
.From("Customers")
)
.WithCTETable(new Table("OrderDetailsWithUnitPriceSuffix"), new SqlQueryBuilder()
.Select()
.Columns("od.OrderID", "p.ProductName", "od.UnitPrice")
.Column(new RIGHT(new CAST(new FLOOR(new Column("od.UnitPrice")), SqlDataType.VARBINARY), 1), "UnitPriceLastDigit")
.From("[Order Details]", "od")
.Join(new List<IJoin>() {
new INNERJOIN().TableName(new Table("Products","p"))
.On(new Column("od.ProductID").Equale(new Column("p.ProductID")))
})
)
.Select()
.Columns("c.CustomerID", "c.CompanyName")
.Column("cps.LastFourDigits", "PhoneLastFour")
.Column("cfx.LastThreeFaxDigits", "FaxLastThree")
.Columns("oud.OrderID", "oud.ProductName", "oud.UnitPrice", "oud.UnitPriceLastDigit")
.From("Customers", "c")
.Join(new List<IJoin>()
{
new LEFTJOIN().TableName(new Table("CustomerPhoneSuffix","cps"))
.On(new Column("c.CustomerID").Equale(new Column("cps.CustomerID"))),
new LEFTJOIN().TableName(new Table("CustomerWithFaxSuffix","cfx"))
.On(new Column("c.CustomerID").Equale(new Column("cfx.CustomerID"))),
new LEFTJOIN().TableName(new Table("OrderDetailsWithUnitPriceSuffix","oud"))
.On(new Column("c.CustomerID").Equale(new SUBSTRING(new CAST(new Column("oud.OrderID"), SqlDataType.VARCHAR),1,5)))
})
.Where(new Where(new IS_NOT_NULL(new Column("cps.LastFourDigits")))
.OR(new IS_NOT_NULL(new Column("cfx.LastThreeFaxDigits")))
.OR(new IS_NOT_NULL(new Column("oud.UnitPriceLastDigit")))
)
.OrderBy(new OrderBy().SetColumnAscending("c.CustomerID"))
.Build();

Query build by SqlQueryBuilder 1

            
WITH CustomerPhoneSuffix
AS (SELECT CustomerID,
           CompanyName,
           Phone,
           RIGHT(Phone, @pMAIN_2507200210130173140) AS LastFourDigits
    FROM Customers
    WHERE LEN(Phone) >= @pMAIN_2507200210130173141),
 CustomerWithFaxSuffix
AS (SELECT CustomerID,
           CompanyName,
           Fax,
           CASE WHEN Fax IS NOT NULL
                     AND LEN(Fax) >= @pMAIN_2507200210130173142 THEN RIGHT(Fax, @pMAIN_2507200210130173143) ELSE NULL END AS LastThreeFaxDigits
    FROM Customers),
 OrderDetailsWithUnitPriceSuffix
AS (SELECT od.OrderID,
           p.ProductName,
           od.UnitPrice,
           RIGHT(CAST (FLOOR(od.UnitPrice) AS VARBINARY), @pMAIN_2507200210130173144) AS UnitPriceLastDigit
    FROM [Order Details] AS od
         INNER JOIN
         Products AS p
         ON od.ProductID = p.ProductID)
SELECT c.CustomerID,
       c.CompanyName,
       cps.LastFourDigits AS PhoneLastFour,
       cfx.LastThreeFaxDigits AS FaxLastThree,
       oud.OrderID,
       oud.ProductName,
       oud.UnitPrice,
       oud.UnitPriceLastDigit
FROM Customers AS c
     LEFT OUTER JOIN
     CustomerPhoneSuffix AS cps
     ON c.CustomerID = cps.CustomerID
     LEFT OUTER JOIN
     CustomerWithFaxSuffix AS cfx
     ON c.CustomerID = cfx.CustomerID
     LEFT OUTER JOIN
     OrderDetailsWithUnitPriceSuffix AS oud
     ON c.CustomerID = SUBSTRING(CAST (oud.OrderID AS VARCHAR), @pMAIN_2507200210130173145, @pMAIN_2507200210130173146)
WHERE cps.LastFourDigits IS NOT NULL
      OR cfx.LastThreeFaxDigits IS NOT NULL
      OR oud.UnitPriceLastDigit IS NOT NULL
ORDER BY c.CustomerID ASC;


            
        

Parameters (If used)

Name Value
@pMAIN_2507200210130173140 4
@pMAIN_2507200210130173141 4
@pMAIN_2507200210130173142 3
@pMAIN_2507200210130173143 3
@pMAIN_2507200210130173144 1
@pMAIN_2507200210130173145 1
@pMAIN_2507200210130173146 5

Query Results 1:

  CustomerID CompanyName PhoneLastFour FaxLastThree OrderID ProductName UnitPrice UnitPriceLastDigit
1 ALFKI Alfreds Futterkiste 4321 545 0
2 ANATR Ana Trujillo Emparedados y helados 4729 745 0
3 ANTON Antonio Moreno Taquería 3932 0
4 AROUT Around the Horn 7788 750 0
5 BERGS Berglunds snabbköp 4 65 67 0
6 BLAUS Blauer See Delikatessen 8460 924 0
7 BLONP Blondesddsl père et fils 5.31 .32 0
8 BOLID Bólido Comidas preparadas 2 82 99 0
9 BONAP Bon app' 5.40 .41 0
10 BOTTM Bottom-Dollar Markets 4729 745 0
11 BSBEV B's Beverages 1212 0
12 CACTU Cactus Comidas para llevar 5555 892 0
13 CENTC Centro comercial Moctezuma 3392 293 0
14 CHOPS Chop-suey Chinese 6545 0
15 COMMI Comércio Mineiro 7647 0
16 CONSH Consolidated Holdings 2282 199 0
17 DRACD Drachenblut Delikatessen 9123 428 0
18 DUMON Du monde entier 8.88 .89 0
19 EASTC Eastern Connection 0297 373 0
20 ERNSH Ernst Handel 3425 426 0
21 FAMIA Familia Arquibaldo 9857 0
22 FISSA FISSA Fabrica Inter. Salchichas S.A. 4 44 93 0
23 FOLIG Folies gourmandes 0.16 .17 0
24 FOLKO Folk och fä HB 7 21 0
25 FRANK Frankenversand 7310 451 0
26 FRANR France restauration 1.21 .20 0
27 FRANS Franchi S.p.A. 8260 261 0
28 FURIB Furia Bacalhau e Frutos do Mar 2534 535 0
29 GALED Galería del gastrónomo 4560 561 0
30 GODOS Godos Cocina Típica 2 82 0
31 GOURL Gourmet Lanchonetes 9482 0
32 GREAL Great Lakes Food Market 7555 0
33 GROSR GROSELLA-Restaurante 2951 397 0
34 HANAR Hanari Carnes 0091 765 0
35 HILAA HILARION-Abastos 1340 948 0
36 HUNGC Hungry Coyote Import Store 6874 376 0
37 HUNGO Hungry Owl All-Night Grocers 542 333 0
38 ISLAT Island Trading 8888 0
39 KOENE Königlich Essen 9876 0
40 LACOR La corne d'abondance 4.10 .11 0
41 LAMAI La maison d'Asie 1.10 .11 0
42 LAUGB Laughing Bacchus Wine Cellars 3392 293 0
43 LAZYK Lazy K Kountry Store 7969 221 0
44 LEHMS Lehmanns Marktstand 5984 874 0
45 LETSS Let's Stop N Shop 5938 0
46 LILAS LILA-Supermercado 6954 256 0
47 LINOD LINO-Delicateses 6-12 -93 0
48 LONEP Lonesome Pine Restaurant 9573 646 0
49 MAGAA Magazzini Alimentari Riuniti 0230 231 0
50 MAISD Maison Dewey 4 67 68 0
51 MEREP Mère Paillarde 8054 055 0
52 MORGK Morgenstern Gesundkost 3176 0
53 NORTS North/South 7733 530 0
54 OCEAN Océano Atlántico Ltda. 5333 535 0
55 OLDWO Old World Delicatessen 7584 880 0
56 OTTIK Ottilies Käseladen 4327 721 0
57 PARIS Paris spécialités 2.66 .77 0
58 PERIC Pericles Comidas clásicas 3745 745 0
59 PICCO Piccolo und mehr 9722 723 0
60 PRINI Princesa Isabel Vinhos 5634 0
61 QUEDE Que Delícia 4252 545 0
62 QUEEN Queen Cozinha 1189 0
63 QUICK QUICK-Stop 5188 0
64 RANCH Rancho grande 5555 556 0
65 RATTC Rattlesnake Canyon Grocery 5939 620 0
66 REGGC Reggiani Caseifici 6721 722 0
67 RICAR Ricardo Adocicados 3412 0
68 RICSU Richter Supermarkt 4214 0
69 ROMEY Romero y tomillo 6200 210 0
70 SANTG Santé Gourmet 2 35 47 0
71 SAVEA Save-a-lot Markets 8097 0
72 SEVES Seven Seas Imports 1717 646 0
73 SIMOB Simons bistro 4 56 57 0
74 SPECD Spécialités du monde 0.10 .20 0
75 SPLIR Split Rail Beer & Ale 4680 525 0
76 SUPRD Suprêmes délices 2 20 21 0
77 THEBI The Big Cheese 3612 0
78 THECR The Cracker Box 5834 083 0
79 TOMSP Toms Spezialitäten 1259 695 0
80 TORTU Tortuga Restaurante 2933 0
81 TRADH Tradição Hipermercados 2167 168 0
82 TRAIH Trail's Head Gourmet Provisioners 8257 174 0
83 VAFFE Vaffeljernet 2 43 44 0
84 VICTE Victuailles en stock 4.86 .87 0
85 VINET Vins et alcools Chevalier 5.10 .11 0
86 WANDK Die Wandernde Kuh 0361 428 0
87 WARTH Wartian Herkku 3655 655 0
88 WELLI Wellington Importadora 8122 0
89 WHITC White Clover Markets 4112 115 0
90 WILMK Wilman Kala 8858 858 0
91 WOLZA Wolski Zajazd 7012 012 0