Tuesday, February 14, 2012

Command USE with variable

Why I can′t use the command USE with variable?

declare @.banco varchar(20)
select @.banco='xpto'
USE @.banco

I have try in other way without success

DECLARE @.banco varchar(50)
declare @.SQL varchar(50)
select @.banco='xpto'
print @.banco
select @.SQL='USE '+@.banco
print @.SQL
exec(@.SQL)

Help me, please.

Rodrigo

It is executed at both compile time and run time, so I presume that is the reason. Not all commands can use variables in place of constants. the TOP command, for instance, only takes constants until it was altered in SQL 2005. For USE sysntax and description:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_tsqlcon_6lyk.asp

|||

I am developing a routine to desfragment
the indexes of all tables of the server... I′ve found one in the books online (DBCC SHOWCONTIG session), but I ′m trying to convert it to defrag all objetcs in all databases of my instance. So I have think in a "Cursor" that get the name of the databases in the "sysdatabases" system table. Than set each database to current and run the script. Fallow the script:

For this, I have think in set the database to run the script on the database context.

Can you help me?

/*Perform a 'USE <database name>' to select the database in which to run the script.*/ -- Declare variables SET NOCOUNT ON DECLARE @.tablename VARCHAR (128) DECLARE @.execstr VARCHAR (255) DECLARE @.objectid INT DECLARE @.indexid INT DECLARE @.frag DECIMAL DECLARE @.maxfrag DECIMAL -- Decide on the maximum fragmentation to allow SELECT @.maxfrag = 30.0 -- Declare cursor DECLARE tables CURSOR FOR SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' -- Create the table CREATE TABLE #fraglist ( ObjectName CHAR (255), ObjectId INT, IndexName CHAR (255), IndexId INT, Lvl INT, CountPages INT, CountRows INT, MinRecSize INT, MaxRecSize INT, AvgRecSize INT, ForRecCount INT, Extents INT, ExtentSwitches INT, AvgFreeBytes INT, AvgPageDensity INT, ScanDensity DECIMAL, BestCount INT, ActualCount INT, LogicalFrag DECIMAL, ExtentFrag DECIMAL) -- Open the cursor OPEN tables -- Loop through all the tables in the database FETCH NEXT FROM tables INTO @.tablename WHILE @.@.FETCH_STATUS = 0 BEGIN -- Do the showcontig of all indexes of the table INSERT INTO #fraglist EXEC ('DBCC SHOWCONTIG (''' + @.tablename + ''') WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS') FETCH NEXT FROM tables INTO @.tablename END -- Close and deallocate the cursor CLOSE tables DEALLOCATE tables -- Declare cursor for list of indexes to be defragged DECLARE indexes CURSOR FOR SELECT ObjectName, ObjectId, IndexId, LogicalFrag FROM #fraglist WHERE LogicalFrag >= @.maxfrag AND INDEXPROPERTY (ObjectId, IndexName, 'IndexDepth') > 0 -- Open the cursor OPEN indexes -- loop through the indexes FETCH NEXT FROM indexes INTO @.tablename, @.objectid, @.indexid, @.frag WHILE @.@.FETCH_STATUS = 0 BEGIN PRINT 'Executing DBCC INDEXDEFRAG (0, ' + RTRIM(@.tablename) + ', ' + RTRIM(@.indexid) + ') - fragmentation currently ' + RTRIM(CONVERT(varchar(15),@.frag)) + '%' SELECT @.execstr = 'DBCC INDEXDEFRAG (0, ' + RTRIM(@.objectid) + ', ' + RTRIM(@.indexid) + ')' EXEC (@.execstr) FETCH NEXT FROM indexes INTO @.tablename, @.objectid, @.indexid, @.frag END -- Close and deallocate the cursor CLOSE indexes DEALLOCATE indexes -- Delete the temporary table DROP TABLE #fraglist GO |||

Here is one way with using sp_MSforeachdb and DBCC DBREINDEXALL

Both of these things are undocumented and you might not want to run it on a production server

EXEC sp_MSForEachDB 'IF ''?'' NOT IN (''master'', ''model'', ''msdb'', ''tempdb'')
DBCC DBREINDEXALL (''?'') '

-- nobody can be connected to the db for the above statement to work

also you could do something like this

DECLARE @.SQL NVarchar(4000)
SET @.SQL = ''
SELECT @.SQL = @.SQL + 'EXEC ' + NAME + '..sp_MSforeachtable @.command1=''DBCC DBREINDEX (''''*'''')'', @.replacechar=''*''' + Char(13)
FROM MASTER..Sysdatabases
where dbid > 6
PRINT @.SQL

EXEC (@.SQL)

However if you exceed 4000 characters this will fail

Denis the SQL Menace

http://sqlservercode.blogspot.com/

|||

For EXECUTE you can use varchar(8000), or in 2005 you can use varchar(max).

|||Please don't use undocumented system stored procedures. They are not guaranteed to remain in every version of SQL Server. In fact we removed several system stored procedures or modified their behavior in SQL Server 2005.|||

Set options or use statement executed within dynamic SQL is only valid within that scope. So in your case, you have to perform the USE and the DBCC statement within the same dynamic SQL execution like:

exec('use ' + @.somedb + '; dbcc index...')

No comments:

Post a Comment