Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Am executing below query but getting error ..
SQL
DECLARE @DataBase VARCHAR(128)
DECLARE @SqlScript VARCHAR(MAX) 
DECLARE DataBaseList CURSOR FOR 
SELECT name FROM SYS.sysdatabases

WHERE NAME NOT IN ('master','tempdb','model','msdb')
-- step 2. insert all the database name and corresponding log files' names into the temp table
OPEN DataBaseList FETCH
NEXT FROM DataBaseList INTO @DataBase
WHILE @@FETCH_STATUS <> -1 
BEGIN

SET @SqlScript = 'USE [' + @DataBase + '] 
INSERT INTO #TransactionLogFiles(DatabaseName, LogFileName) 
SELECT '''+ @DataBase + ''', Name FROM sysfiles WHERE FileID=2'
--SELECT @SqlScript
EXEC(@SqlScript) 
FETCH NEXT FROM DataBaseList INTO @DataBase END

DEALLOCATE DataBaseList

-- step 3. go through the each row and execute the shrinkfile script against each database log file on the server
DECLARE TransactionLogList CURSOR FOR 
SELECT DatabaseName, LogFileName FROM #TransactionLogFiles 
DECLARE @LogFile VARCHAR(128) 

OPEN TransactionLogList FETCH
NEXT FROM TransactionLogList INTO @DataBase, @LogFile
WHILE @@FETCH_STATUS <> -1 
BEGIN 
SELECT @SqlScript = 'USE [' + @DataBase + '] '
+ 'ALTER DATABASE [' + @DataBase + '] SET RECOVERY SIMPLE WITH NO_WAIT '
+ 'DBCC SHRINKFILE(N''' + @LogFile + ''', 1) '
+ 'ALTER DATABASE [' + @DataBase + '] SET RECOVERY FULL WITH NO_WAIT'
EXEC(@SqlScript) 

FETCH NEXT FROM TransactionLogList INTO @DataBase, @LogFile END
DEALLOCATE TransactionLogList
--SELECT * FROM #TransactionLogFiles

-- step 4. clean up
--DROP TABLE #TransactionLogFiles



error is like in below

Msg 208, Level 16, State 0, Line 2
Invalid object name '#TransactionLogFiles'.
Posted
Updated 9-Sep-15 23:15pm
v2

1 solution

The hash ('#') denotes a temporary table. It may not persist after it's creation.

Try this instead:
SQL
SET @SqlScript = 'USE [' + @DataBase + '] 
SELECT 
    '''+ @DataBase + ''' as DatabaseName, 
    Name as LogFileName
INTO #TransactionLogFiles(DatabaseName, LogFileName) 
 FROM sysfiles WHERE FileID=2'


This syntax will create the table if it does not already exist.

If you want an identity column then you will have to create the table first.

It is always good practice to create and delete temporary tables from within the procedure. That way you will know when it exists and when it does not.

Hope that helps ^_^
Andy
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900