Marius
Marius

Reputation: 597

Is there a way to shorten my SQL Server code

I'm quite new to SQL server and basically I have this query that uses two table and I was wondering if there's an easy way to shorten the code, the repeating of the table names looks pretty bad.

SELECT        
    dbo.atbl_Sales_OrdersLines.OrderID, dbo.atbl_Sales_OrdersLines.Created, 
    dbo.atbl_Sales_OrdersLines.CreatedBy, dbo.atbl_Sales_OrdersLines.Updated, 
    dbo.atbl_Sales_OrdersLines.UpdatedBy, 
    dbo.atbl_Sales_OrdersLines.CUT, dbo.atbl_Sales_OrdersLines.CDL, 
    dbo.atbl_Sales_OrdersLines.Domain, dbo.atbl_Sales_OrdersLines.ProductID, 
    dbo.atbl_Sales_OrdersLines.Amount, dbo.atbl_Sales_Products.ProductName, 
    dbo.atbl_Sales_Products.Supplier, dbo.atbl_Sales_Products.Quantity AS TotalQuantity, 
    dbo.atbl_Sales_Products.Price, dbo.atbl_Sales_OrdersLines.PrimKey
FROM
    dbo.atbl_Sales_OrdersLines 
INNER JOIN
    dbo.atbl_Sales_Products ON dbo.atbl_Sales_OrdersLines.ProductID = dbo.atbl_Sales_Products.ProductID

There has to be an easier way to do this. Thank you.

Upvotes: 0

Views: 92

Answers (1)

marc_s
marc_s

Reputation: 754973

Use tables alias to shorten that code:

SELECT        
    ol.OrderID, 
    ol.Created, ol.CreatedBy, ol.Updated, ol.UpdatedBy, 
    ol.CUT, ol.CDL, 
    ol.Domain, ol.ProductID, ol.Amount,  
    p.ProductName, p.Supplier, p.Quantity AS TotalQuantity, p.Price, 
    ol.PrimKey
FROM
    dbo.atbl_Sales_OrdersLines ol
INNER JOIN
    dbo.atbl_Sales_Products p ON ol.ProductID = p.ProductID

The ol and p are table alias that you can choose - I recommend choosing something that is "intuitive", e.g. "ol" for "Order Lines", "p" for "Product" - that makes reading (and understanding) your SQL code much easier

Upvotes: 4

Related Questions