Freek's Blog

SQL en .NET vraagstukken en oplossingen die ik zoal tegenkom
posts - 199, comments - 123, trackbacks - 2, articles - 7

My Links

News

Google analytics script: Locations of visitors to this page

Article Categories

Archives

Post Categories

Image Galleries

Algemene links

MSDN

vb links

Thursday, June 10, 2010


How to determine if a temp table already exists? Well, I found this sql script that works fine for me!
If the temptable already exists it will be dropped by the last line in the code.


if exists (
select * from tempdb.dbo.sysobjects o
where o.xtype in ('U')
and o.id = object_id(N'tempdb..#tablename')
)
drop table #tablename

posted @ 4:21 PM | Feedback (0)

In this case I wanted to get the record count of a table and pass this number to another table for reporting services.
But how to get the number of records into a variable?

Well by using executesql  procedure.
This procedure is divided into 3 parts:
1. the command with parameter(s)
2. the parameters                                      = contains the values mentioned in the command
3. the values                                              = contains the returning values

see also: h t t p ://www.databasejournal.com/features/mssql/article.php/3286501/T-SQL-Programming-Part-4---Setting-Variables-in-Calling-T-SQL-Code-While-Using-spexecutesql.htm


the code I used was:

declare @tblName as varchar(20)
set @tblName = 'tablename'
declare @RECCNT int
declare @CMD Nvarchar(100)


SET @CMD = 'SELECT @RECORDCNT=count(*) from ' + @tablename

print @CMD

exec sp_executesql @CMD,
                              N'@RECORDCNT int out',
                             @RECCNT out

print @reccnt

 

result:

SELECT @RECORDCNT=count(*) from tablename

97954

 

posted @ 1:25 PM | Feedback (0)