Question : Alternative to a cursor

The sql script below is an example to show you what I am trying to do on another database. It counts the number of records in a database and then add's a new column called 'TYPE', which gets populated by a UPDATE statement using CASE.

Is there another way to do this that is quicker and doesn't require creating a table, maybe a while loop.

Thank you
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
IF OBJECT_ID(N'AUDIT_REC_COUNT', N'U') IS NOT NULL 
DROP TABLE AUDIT_REC_COUNT;
GO
CREATE TABLE [AUDIT_REC_COUNT](TABLENAME varchar(50), [COUNT] NUMERIC)
GO

DECLARE @Count TABLE (
            [TABLENAME] VARCHAR(20) COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL ,            
            [COUNT] FLOAT NULL)

DECLARE @tablename AS VARCHAR(50)

DECLARE Record_Count CURSOR FOR
SELECT [NAME] [ATTRIB] FROM sys.tables

OPEN Record_Count

FETCH NEXT FROM Record_Count
INTO @tablename
WHILE @@FETCH_STATUS = 0
BEGIN
 	exec('insert into AUDIT_REC_COUNT(TABLENAME, [COUNT])
	select '''+@tablename+''', count(*) from '+@tablename+'')
    FETCH NEXT FROM Record_Count
    INTO @tablename
END

CLOSE Record_Count
DEALLOCATE Record_Count
GO

ALTER TABLE AUDIT_REC_COUNT
ADD TYPE varchar(50)
GO

UPDATE AUDIT_REC_COUNT SET TYPE = 
(CASE WHEN TABLENAME LIKE '%_fallback_%' THEN 'fallback'
	  WHEN TABLENAME LIKE '%_monitor%' THEN 'monitor' 
ELSE NULL END
)
GO


SELECT * FROM [AUDIT_REC_COUNT] WHERE count > 0
ORDER BY TABLENAME

Answer : Alternative to a cursor

You can force protocol encryption. This forces all communication to be SSL encrypted. Therefore if anoyone sniffs the packets, they can't make any sense of the data.

There is some overhead in this - you need to deploy certificates to clients, set up certificates on the SQL Server. There is also proecssing overhead in encrypting and decrypting the data.

http://msdn.microsoft.com/en-us/library/ms189067.aspx

Random Solutions  
 
programming4us programming4us