Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL - Select Count(*) ..into Varchar variable

let's say I have 10 tables and I need to write a simple LOG entry that states how many records each tables has.

Something like

Declare @msg Varchar(MAX)
Set @msg = 'Process Succeeded; Table1 has xx record, Table2 has zz records, Table3 has ww records ...'

Insert INTO LOG (msg) VALUES (@msg)
like image 429
SF Developer Avatar asked May 12 '26 19:05

SF Developer


2 Answers

Or roll it up into:

 declare @Summary as VarChar(256)
 select @Summary =
   'Foo: ' + Cast( ( select Count(42) from Foo ) as VarChar(10) ) +
   ', Bar: ' + Cast( ( select Count(42) from Bar) as VarChar(10) )
 select @Summary
like image 72
HABO Avatar answered May 14 '26 10:05

HABO


Since SQL Server currently does not have any support for something like string.Format, you have to do:

DECLARE @msg VARCHAR(MAX)

DECLARE @Table1Count INT
SELECT @Table1Count = COUNT(*) FROM dbo.Table1 

DECLARE @Table2Count INT
SELECT @Table2Count = COUNT(*) FROM dbo.Table2

..... and so forth for each table you want to consider

SET @msg = 'Process Succeeded; ' + 
    'Table1 has ' + CAST(@Table1Count AS VARCHAR(10)) + ' rows, ' + 
    'Table2 has ' + CAST(@Table2Count AS VARCHAR(10)) + ' rows...' + ........

Insert INTO LOG (msg) VALUES (@msg)

Right now, in SQL Server, this is a pain - that's why it might be a lot easier to just return those counts to a front-end app and do the formatting and log writing there.

SQL Server 2012 will have a FORMAT function (long overdue!)

like image 33
marc_s Avatar answered May 14 '26 11:05

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!