I am not able to append the current value of @msg with the newest values. It is ok with the 1st @msg as it prints out all values but when it comes to 2nd @msg, it returns only the latest value. I have an idea to create a temporary table for storing newest values. What would you suggest in this situation?
FETCH NEXT FROM c_fileList INTO @dbName, @filename
WHILE @@FETCH_STATUS = 0
BEGIN
SET @msg = 'Delete backup file: ' + @filename + ' For Database: ' + @dbName
PRINT @msg
FETCH NEXT FROM c_fileList INTO @dbName, @filename
END
PRINT @msg
SET @msg = 'Delete...'
doesn't concatenate the value for @msg
, it reassigns it. if you want to concatenate the value, it would be SET @msg = @msg + 'Delete...'
.
Seems like this would be much easier with STUFF
and FOR XML PATH
though. A Cursor is an awfully slow way to make what is effectively a delimited list.
DECLARE @msg nvarchar(4000);
SET @msg = STUFF((SELECT NCHAR(10) +
N'Delete backup file: ' + {FileName Column} + N' for Database: ' + {DBName Column}
FROM YourTable
--ORDER BY ???
FOR XML PATH(N''),TYPE).value('.','nvarchar(4000)'),1,1,N'');
PRINT @Msg;
As should already be obvious, this will truncate any value longer than 4,000 characters (which is the max length for a PRINT
).
if my assumption about what you're trying to accomplish, and how you're doing it, is correct, you don't need a cursor or a temp table:
IF OBJECT_ID('tempdb..#tempFiles', 'U') IS NOT NULL
DROP TABLE #tempFiles
CREATE TABLE #tempFiles
(
RecordID INT IDENTITY(1, 1) NOT NULL
, DBName VARCHAR(32)
, DBFileName VARCHAR(32)
)
INSERT INTO #tempFiles VALUES
('DBOne', 'c:\DBOnefileone.mdf')
, ('DBOne', 'c:\DBOnefiletwo.mdf')
, ('DBOne', 'c:\DBOnefilethree.mdf')
, ('DBOne', 'c:\DBOnelogfileone.ldf')
, ('DBTwo', 'c:\DBTwofileone.mdf')
, ('DBTwo', 'c:\DBTwologfileone.ldf')
DECLARE @msg VARCHAR(MAX) = ''
SELECT @msg = @msg + 'Delete backup file: ' + DBFileName + ' For Database: ' + DBName + CHAR(13) + CHAR(10)
FROM #tempFiles
ORDER BY RecordID
print @msg
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.