Showing posts with label sql server. Show all posts
Showing posts with label sql server. Show all posts

Tuesday, May 08, 2012

Sql Server 2008, disk space

Found these commands useful, when dealing with Sql Server 2008 disk space allocation and log shrinking; in sql 2008 as you probably know you cannot use any more the command BACKUP LOG databasename WITH TRUNCATE ONLY as shown for example here: to obtain the same result you can do the following:

alter database [database_name] set recovery simple        
go
checkpoint        
go
alter database [database_name] set recovery full        
go
backup database [database_name] to disk = 'd:\temp\filename.bak' with init        
go
dbcc shrinkfile (N'DATABASE_NAME_log' , 1)        
go

To monitor disk space allocated, check for the usage of

EXEC sp_spaceused @updateusage = N'TRUE';

The following procedure uses the sp_spaceused procedure to list each table’s space:

CREATE PROCEDURE GetAllTableSizes      
AS
-- Lists spaced used data for ALL user tables in the database
DECLARE @TableName VARCHAR(100)    --For storing values in the cursor
--Cursor to get the name of all user tables from the sysobjects listing
DECLARE tableCursor CURSOR
FOR
    select [name]
    from dbo.sysobjects
    where  OBJECTPROPERTY(id, N'IsUserTable') = 1
FOR READ ONLY
--A procedure level temp table to store the results      
CREATE TABLE #TempTable
(
    tableName varchar(100),
    numberofRows varchar(100),
    reservedSize varchar(50),
    dataSize varchar(50),
    indexSize varchar(50),
    unusedSize varchar(50)
)
--Open the cursor      
OPEN tableCursor
--Get the first table name from the cursor      
FETCH NEXT FROM tableCursor INTO @TableName

--Loop until the cursor was not able to fetch      
WHILE (@@Fetch_Status >= 0)
BEGIN
    --Dump the results of the sp_spaceused query to the temp table
    INSERT  #TempTable
        EXEC sp_spaceused @TableName

    --Get the next table name      
    FETCH NEXT FROM tableCursor INTO @TableName
END
--Get rid of the cursor      
CLOSE tableCursor
DEALLOCATE tableCursor
--Select all records so we can use the reults      
SELECT *
FROM #TempTable
--Final cleanup!      
DROP TABLE #TempTable
GO 

Thursday, September 01, 2011

Sql Server–find some texts in Stored Procedures

I often need to search for some texts in the body of stored procedures. This query can help:

SELECT routine_name, routine_definition
FROM information_schema.routines
WHERE UPPER(routine_definition) LIKE UPPER('%texttobesearched%')
AND routine_type='procedure'

EDIT: just discovered that this method has some problems with long stored procedures; found another one that works better:

declare @searchString varchar(100)

Set @searchString = '%' + 'text to be searched' + '%'

SELECT Distinct SO.Name
FROM sysobjects SO (NOLOCK)
INNER JOIN syscomments SC (NOLOCK) on SO.Id = SC.ID
AND SO.Type = 'P'
AND SC.Text LIKE @searchString
ORDER BY SO.Name

Wednesday, March 23, 2011

Sql Server Management Studio & “WTF”

Open Sql ServerManagement Studio, Open a New Query, Type WTF and press Enter.

Have fun.

Monday, August 02, 2010

Sql Server Fragmentation

Found in an article on SqlServerCentral (VERY useful site), some scripts that show the fragmentation degree of your database objects:

-- check fragmentation on @db
Declare @db     SysName;
Set @db = 'MCD_SAWFC_PROD';

SELECT CAST(OBJECT_NAME(S.Object_ID, DB_ID(@db)) AS VARCHAR(20)) AS 'Table Name',
CAST(index_type_desc AS VARCHAR(20)) AS 'Index Type',
I.Name As 'Index Name',
avg_fragmentation_in_percent As 'Avg % Fragmentation',
record_count As 'RecordCount',
page_count As 'Pages Allocated',
avg_page_space_used_in_percent As 'Avg % Page Space Used'
FROM sys.dm_db_index_physical_stats (DB_ID(@db),NULL,NULL,NULL,'DETAILED' ) S
LEFT OUTER JOIN sys.indexes I On (I.Object_ID = S.Object_ID and I.Index_ID = S.Index_ID)
AND S.INDEX_ID > 0
ORDER BY avg_fragmentation_in_percent DESC

The following SQL can be used to rebuild all indexes for the specified table;

ALTER INDEX ALL ON <Table Name> REBUILD;


while the following SQL can be used to rebuild a specific index.



ALTER INDEX <Index Name> ON <Table Name> REBUILD;


Alternatively, indexes can be reorganised. The following SQL can be used to reorganise all indexes for the specified table;



ALTER INDEX ALL ON <Table Name> REORGANIZE; 


while the following SQL can be used to reorganise a specific index.



ALTER INDEX <Index Name> ON <Table Name> REORGANIZE; 

Tuesday, May 11, 2010

SOLVED: Sql Server 2008 log shipping on servers not in same domain

Lately I suffered some headache trying to set up log shipping on a couple of Sql Server 2008 machines.

In my farm, the “second” server arrived when the first was already running, responding to a high traffic website. And the two servers are not in the same domain – actually they are not in any domain.

I won’t enter in detail on how to set up log shipping, follow the wizard, it’s quite easy (to reach the wizard: right click on a db, choose Tasks, then “Ship transaction logs”).

When you set up log shipping, and the servers are in the same domain, you have little problems: you need to create a couple of file share on the two servers, and give read permissions to accounts running the Sql Server Agent service “on the other” server. But that is quite easy, follow instructions and it’s done.

A different story is when the shipping server don’t know anything of the “shipped” one. I tried different configuration, but I always end in “Access denied” errors.

At last I found this answer on Serverfalult.com, and that was the path to follow. The answer is about Sql 2005, but the same works on sql 2008.

In brief, here’s what I did:
- created an account on the two servers, with exactly the SAME NAME and the SAME PASSWORD, and put the user in Administrators group
- changed identity (“log on” tab) of both Sql Server Agent AND Sql Server services (only Agent did not suffice) on both servers
- gave read permission on the share used in the log shipping configuration

Done all that, when I ran the log shipping job they started working immediately.

Now I’m not a windows authentication guru, but all this looks a little crazy to me… but hey, who cares! Now log shipping works… :-)

Thursday, November 19, 2009

Sql server getdate() – set to midnight

a very short note on a particular use of getdate() to obtain the today’s date with hours minutes and seconds set to midnight (00:00:00):

select dateadd(day, datediff(day, 0, getdate()), 0)

Friday, November 06, 2009

Sql Server Restore

 

Some statements I found useful to recover a database backup applying some transaction logs (had to step into this due to a wrong delete operation on a production database – no, it wasn’t me…).

RESTORE DATABASE [TheDatabase]
FROM DISK = 'D:\foldername\bak\FULL_20091102_024436.bak'
WITH
MOVE 'TheDatabase_Data' TO 'D:\Program Files\Microsoft SQL Server\MSSQL\Data\TheDatabase_Data.mdf',
MOVE 'TheDatabase_log' TO 'D:\Program Files\Microsoft SQL Server\MSSQL\Data\TheDatabase_Log.ldf',
NORECOVERY

RESTORE LOG [TheDatabase] FROM DISK = 'D:\foldername\bak\20091102_060214.bak' WITH NORECOVERY

RESTORE LOG [TheDatabase] FROM DISK = 'D:\foldername\bak\20091103_180221.bak' WITH NORECOVERY

[…]

RESTORE LOG [TheDatabase] FROM DISK = 'D:\foldername\bak\20091105_000219.bak' WITH NORECOVERY

RESTORE LOG [TheDatabase] FROM DISK = 'D:\foldername\bak\20091105_060204.bak' WITH RECOVERY

Some comments: the NORECOVERY option used in all the statement but one causes Sql Server to leave the db in a non operational state; this is needed because we will apply other restore statements. In the last one I use the RECOVERY option, in order to put the database in operational state.

Obviously this is only a little part of the big big world of database maintenance: just to say, give a look at the RESTORE command syntax… http://msdn.microsoft.com/en-us/library/ms186858.aspx

Bye!

Sunday, October 25, 2009

Azure Sql Services – let’s try!

I decided to ask for a test account in the preview phase of Azure sql services, and today I’m trying to connect to it.

The signup process is quite easy and simple; once logged, I reach the web administration console for my databases.

I created my first db, 1gb maximum size. Now I want to connect to it using SSMS (Sql Server Management Studio) from my laptop. In the console there is a useful link to ready made “connection strings”, I use them to fill the SSMS connection dialog – but hey! I cannot connect…

After some clicking around I notice that I can setup the “firewall rules” in order to gain access from my IP. Let’s try.

The connection error actually states that I cannot connect from 78.14.234.1, so I fill the form to setup a “grant access” rule, as in the screenshot below:

Now I can connect successfully! And I can launch a New Query against my db, and run some (useless, I know) statements like:

The statements are quite silly, just to prove that I can do DDL.

Now I see that I cannot use the SSMS native “Object Explorer”, and looks like it’s impossible.

Looks like there are some alternative tool in this field, with some limitation (it’s a brave new world…); for example http://hanssens.org/tools/sqlazuremanager/ – Sql Azure Manager; is a tool developed to connect to Azure. It’s a ClickOnce setup, around 3.76 Mb in size. Once downloaded and installed, it prompts for your database connection parameter and you’re in.

There is also a web-based tool, Omega.MSSQL, at https://onlinedemo.cerebrata.com/SQLAzureClient/default.aspx. I cannot connect through this, but I found good opinions on it, so maybe it’s a problem on my side.

Another tool: “Gem Query Tool for Sql Azure”, here: http://microguru.com/gem/ – it’s very simple and lacks a lot of features… but again, I think that all these tools are too young to tell.

So far so good. I’ll keep you informed on this subject as I understand better. Bye!

Friday, April 18, 2008

A couple of Sql Server (useful) things

1) Changing sa password

A couple of days ago I discovered with horror that I forgot my "sa" password, on my sql 2005 local instance.

To solve this, googling around I found this couple of methods:

USE MASTER

ALTER LOGIN [sa] WITH PASSWORD=N'new_password'

or from a command prompt

    OSQL -S <server_name> -E
    1> EXEC sp_password NULL, 'new_password', 'sa'
    2> GO

2) Transact sql Split function

I needed a split function, and I fpound this good forum discussion exactly on this topic:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648

I used this one:

CREATE FUNCTION dbo.Split
(
@RowData nvarchar(2000),
@SplitOn nvarchar(5)

RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS 
BEGIN
Declare @Cnt int
Set @Cnt = 1

While (Charindex(@SplitOn,@RowData)>0)
Begin
  Insert Into @RtnValue (data)
  Select
   Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

  Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
  Set @Cnt = @Cnt + 1
End
 
Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))

Return
END

Wednesday, January 16, 2008

Survival: Sql Server, change ownership on stored procedures

Some time ago I wrote about a couple of methods to grant execution permission on stored procedures, on Sql Server 2000.

Now I had to write something similar, but the scope was to change ownership of the objects; after some googling I found this page on support.microsoft.com that lists a good way to do the job... but I modified slightly the code from MS, because I needed the possibility to decide to actually execute the commands or simply print them.

So I added a simple parameter (the third), datatype bit, default 0 (false). When set to 1 (true) will cause the execution of the commands.

Here's the code:

CREATE PROCEDURE [dbo].[chObjOwner]( @usrName varchar(20), @newUsrName varchar(50), @exec bit = 0)
as
-- @usrName is the current user
-- @newUsrName is the new user

set nocount on
declare @uid int                   -- UID of the user
declare @objName varchar(50)       -- Object name owned by user
declare @currObjName varchar(50)   -- Checks for existing object owned by new user
declare @outStr nvarchar(256)       -- SQL command with 'sp_changeobjectowner'
set @uid = user_id(@usrName)

declare chObjOwnerCur cursor static
for
select name from sysobjects
where 1=1
AND uid = @uid
AND xtype in ( 'P', 'U', 'V')
and name <> 'chObjOwner'
-- category: zero is valid for Stored Procedures... but not for tables
-- and category = 0

open chObjOwnerCur
if @@cursor_rows = 0
begin
  print 'Error: No objects owned by ' + @usrName
  close chObjOwnerCur
  deallocate chObjOwnerCur
  return 1
end

fetch next from chObjOwnerCur into @objName

while @@fetch_status = 0
begin
  set @currObjName = @newUsrName + '.' + @objName
  if (object_id(@currObjName) > 0)
    print 'WARNING *** ' + @currObjName + ' already exists ***'
  set @outStr = 'sp_changeobjectowner ''' + @usrName + '.' + @objName + ''',''' + @newUsrName + ''''
  print @outStr
  IF @exec = 1
    execute sp_executesql @outStr
  --print 'go'
  fetch next from chObjOwnerCur into @objName
end

close chObjOwnerCur
deallocate chObjOwnerCur
set nocount off
return 0

La Castro Taqueria is changing to Kasa Indian Eatery, it seems.

Tuesday, April 17, 2007

Sql Server, remove duplicate records

Sometimes I need to remove duplicates from a table, given a particular column to be checked.

This few lines of transact-sql code will help, I hope:

CREATE TABLE #tmp_tableCleanDup (id int, email varchar(200))
CREATE UNIQUE CLUSTERED INDEX pk ON #tmp_tableCleanDup(ID)
CREATE UNIQUE INDEX removeduplicates on #tmp_tableCleanDup (email) WITH IGNORE_DUP_KEY

BEGIN TRANSACTION

 INSERT #tmp_tableCleanDup
 SELECT e.ID, e.email
 FROM OriginalTable e

 DELETE OriginalTable
 WHERE 1=1
 AND id NOT IN (SELECT id FROM  #tmp_tableCleanDup)

COMMIT TRANSACTION

 DROP TABLE #tmp_tableCleanDup

Friday, January 05, 2007

Survival: Sql Server, grant on all stored procedure and shrink db and logs

1) Stored Procedures: to grant execute permission on all the stored procedures in a database, use this (quick and dirty) solution:

use DATABASE_NAME

select 'grant execute on ' + specific_name + ' to [LOGIN_NAME] '
from  information_schema.routines
where routine_type = 'PROCEDURE'

executing this after the obvious substitutions of LOGIN_NAME and DATABASE_NAME will return a bunch of lines like

grant execute on stored_procedure_name to [LOGIN_NAME]

if you copy and execute those lines, you're done.

2) Stored Procedures: another (less dirty) way to obtain the same result:

DECLARE @proc_name  SYSNAME
DECLARE @sql   VARCHAR(4000)
DECLARE @username  VARCHAR(255)

SET @username = 'LOGIN_NAME_HERE'
SET @proc_name = ''

WHILE 1=1
 BEGIN
  SET @proc_name = (SELECT TOP 1 ROUTINE_NAME
     FROM INFORMATION_SCHEMA.ROUTINES
     WHERE OBJECTPROPERTY(OBJECT_ID(ROUTINE_NAME), 'IsMSShipped') = 0
   -- Only user stored procedures here!
    AND ROUTINE_TYPE = 'PROCEDURE'
    AND ROUTINE_NAME > @proc_name
    ORDER BY ROUTINE_NAME
  )
  IF @proc_name IS NULL BREAK
  SET @sql = 'GRANT EXECUTE ON ' + QUOTENAME(@proc_name) + ' TO ' + @username
 EXEC (@sql)
 --Print (@sql)
 END

3)  Shrink database and transaction log: Just a couple of instructions that sometimes are useful to shrink databases log files:

BACKUP LOG  databasename  WITH TRUNCATE_ONLY
 
DBCC SHRINKFILE (  databasename_Log  , 1)

DBCC SHRINKDATABASE (databasename, 10)