When assigning a variable, is there a functional difference between set and select?
I often write scripts that have to iterate through processes, and on each iteration I update a variable with a value.
For example, my company's product has multiple servers, on each server we have a certain number of databases that our clients data resides in. Each database has between 5 and 50 clients. A table in a primary database indicates which of the individual databases each client is on. Today I found a problem with the primary key on one table, and we need to modify the primary key to add a column to it. The table on each database may have several hundred thousand records, so we expect the updates to take some time. We need to do these overnight to avoid performance issues. So I've written the following script to iterate through the process on each database (I'll execute it separately on each server):
DECLARE @DBTABLE TABLE
(
TableID INT IDENTITY PRIMARY KEY NOT NULL,
DbName VARCHAR(50) NOT NULL,
ServerName VARCHAR(50) NOT NULL,
ProcFlag INT NOT NULL DEFAULT 0
)
INSERT INTO @DBTABLE (DbName, ServerName)
SELECT DISTINCT DbName, ServerName
FROM PrimaryDatabase.dbo.Cients WITH(NOLOCK)
WHERE ClientInactive = 0
AND ServerName = @@SERVERNAME
DECLARE @TABLETEST INT
DECLARE @TABLEID INT
DECLARE @DBNAME VARCHAR(50)
DECLARE @SERVERNAME VARCHAR(50)
DECLARE @VAR_SQL VARCHAR(MAX)
SET @TABLETEST = (SELECT COUNT(*) FROM @DBTABLE WHERE ProcFlag = 0)
WHILE @TABLETEST > 0
BEGIN
SET @TABLEID = (SELECT MIN(TableID) FROM @DBTABLE WHERE ProcFlag = 0)
SET @DBNAME = (SELECT DbName FROM @DBTABLE WHERE TableID = @TABLEID)
SET @SERVERNAME = (SELECT ServerName FROM @DBTABLE WHERE TableID = @TABLEID)
SET @VAR_SQL = '
ALTER TABLE ' + @DBNAME + '.dbo.ClientDealTable DROP CONSTRAINT [PK_ClientDealTable]
ALTER TABLE ' + @DBNAME + '.dbo.ClientDealTable ADD CONSTRAINT [PK_ClientDealTable] PRIMARY KEY CLUSTERED ([ClientID] ASC, [DealNumber] ASC, [DealDate] ASC)
'
EXEC(@VAR_SQL)
UPDATE @DBTABLE SET ProcFlag = 1 WHERE TableID = @TABLEID
SET @TABLETEST = (SELECT COUNT(*) FROM @DBTABLE WHERE ProcFlag = 0)
END
Is SET
or SELECT
the preferred option here, or does it really matter? Is there a performance difference?