Wednesday, January 15, 2020

T-SQL: SET ROWCOUNT 0

Why is this phrase used all over the place in stored procs?  Well, if someone has used "SET ROWCOUNT 1" or to some other number, you need to turn that off! So using "0" turns it off.  It does not set the rowcount to ZERO!!!

T-SQL: CURSOR

drop table #Practitioner;
   select userId as PractitionerId into #Practitioner from tblUsers
  where userStatus = 'Needs to be researched';


DECLARE @PractitionerId NVARCHAR(MAX)

DECLARE MY_CURSOR CURSOR
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT DISTINCT PractitionerId
FROM #Practitioner

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @PractitionerId
WHILE @@FETCH_STATUS = 0
BEGIN
    --Do something with Id here
    PRINT @PractitionerId
    FETCH NEXT FROM MY_CURSOR INTO @PractitionerId
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR

T-SQL LOOPS

Aint no for...loops in T-SQL, so you can use something like:

DECLARE @cnt INT = 0;
WHILE @cnt < 10
BEGIN
   PRINT 'Inside simulated FOR LOOP';
   SET @cnt = @cnt + 1;
END;

PRINT 'Done simulated FOR LOOP';

--------------------------------------------------------------------------------
Practical example to create a reporting hierarchy for an org chart:

DECLARE @userid NVARCHAR(10) = 'A1234'
WHILE @userid is not null
    BEGIN
         select * from tblUsers where userId = @userid
         set @userid  = (select supervisorsUserId from tblUsers where userId = @userid )
    END

-------------------------------------------------------------------------------
Another example, using PRINT and multiple variables:

DECLARE @UserId NVARCHAR(10) = 'A1234',
 @FirstName NVARCHAR(max),
 @LastName NVARCHAR(max);

WHILE @UserId is not null
    BEGIN
         select @FirstName=FirstName, @LastName=LastName
         from tblUsers where UserId = @UserId
         PRINT @FirstName + ' ' + @LastName + ' reports to '
         set @UserId  = (select SupervisorsUserId from tblUsers where UserId = @UserId )
    END


=============================================
You can nest BEGIN...END's!!
=============================================

If you need to insert a "break" (like an "exit"), here's how:

BEGIN

 -- do stuff
--- would cause an infinite loop if not caught!!
IF EXISTS (select userID from tblUsers where SupervisorsUserId = @UserId)
BEGIN
     BREAK;
END



END

Friday, January 10, 2020

How the Astrolabe was even more similar to modern day computers

In the Reader's Guide to the History of Science edited by Arne Hessenbruch we find the following, by Michael Wintroub, which reminds me of many a computer program, or at least their features: