Comments on: T-SQL BEST Practices https://codingsight.com/t-sql-best-practices/ Blog for SQL Server DBAs and Developers Fri, 07 Oct 2022 07:14:17 +0000 hourly 1 https://wordpress.org/?v=6.5.2 By: Lynn Pettis https://codingsight.com/t-sql-best-practices/#comment-331 Wed, 15 Sep 2021 15:11:51 +0000 http://codingsight.com/?p=3368#comment-331 Your tips are good. There are couple of issues with two of them, however, that should be addressed.

Avoid correlated subqueries.

This query:

SELECT
p.Name AS ProductName
, (SELECT pc.Name
FROM Production.ProdutCategory AS pc
WHERE pc.ProductCategoryID = p.ProductSubcategoryID
) AS ModelName
FROM
Prodution.Product AS p;

May not be equvilent to this query:

SELECT
p.Name AS ProducctName
, pc.Name AS ModelName
FROM
Prodution.Product AS p
LEFT JOIN Prodution.ProductCategory AS pc — Left inner join from Product to ProductCategory
ON pc.ProductCategoryID = p.ProductSubcategoryID;

The first query could have NULL values returned by the subquery. This would not be
the case it there was a foreign key relationship between Product and ProductCategory
where the values in ProductSubcategoryID must exist in ProductCategoryID.

If NULL values are possible, then the new query would need to look like this:

SELECT
p.Name AS ProducctName
, pc.Name AS ModelName
FROM
Prodution.Product AS p
LEFT OUTER JOIN Prodution.ProductCategory AS pc
ON pc.ProductCategoryID = p.ProductSubcategoryID;

Use small batcches in delete an upddate statements.

The original script in the article will work when being run manually in SSMS.
However, if you are writing a procedure, the code provided won’t work.
You will need something like this:

DECLARE @BatchSize int
, @LoopSize int
, @LoopCnt int;

SET @BatchSize = 1000;
SET @LoopSize = CEILING((1.0 * (SELECT COUNT(*)
FROM Sales.SalesOrderDetail AS sod
WHERE sod.CarrierTrackingNumber IS NULL
)
) / @BatchSize
);
SET @LoopCnt = 0;
WHILE @LoopCnt < @LoopSize
BEGIN
BEGIN TRAN
UPDATE TOP(@BatchSize) Sales.SalesOrderDetail SET
CarrierTrackingNumber = 'NewNumber_01'
WHERE CarrierTrackingNumber IS NULL;
COMMIT TRAN;
SET @LoopCnt += 1;
END;

]]>
By: 5 Useful Tips for Using SQL Server UPDATE Query with JOIN https://codingsight.com/t-sql-best-practices/#comment-330 Tue, 14 Sep 2021 12:53:28 +0000 http://codingsight.com/?p=3368#comment-330 […] T-SQL Best Practices […]

]]>
By: --Jeff Moden https://codingsight.com/t-sql-best-practices/#comment-123 Sat, 24 Feb 2018 01:35:00 +0000 http://codingsight.com/?p=3368#comment-123 Nice tips. Just a suggestion, though. If all someone is going to do is regurgitate the same error that SQL Server generates, then forget the Try-Catch and let SQL Server do it’s job.

]]>