Friday 25 January 2013

MS SQL delete data from all tables

   According to my task I have to migrate data from Sybase Adaptive Anywhere to MS SQL Server. Before migration data need delete data in target database. For this purpose, of course,  we can use classic command like DELETE FROM ..... for each table or use CURSOR it is more proffesional. I use more nice solution with stored procedure sp_msForEachTable. Pay attention that this procedure is undocumented and may go away or be modified  at any time. 

Example:
  

use HeatService;
exec sp_msforeachtable @command1 = "delete from  ?"


 or delete all except dbo.sysdiagrams

use HeatService;
exec sp_msforeachtable @command1 = "if '?' <> '[dbo].[sysdiagrams]'
begin
delete from  ?
end"



Also you have to know about sp_msForEachdDB sister of  sp_msForEachTable. 
Getting list databases:


exec sp_msforeachdb @command1= "select '?'"