Posts tonen met het label SQL. Alle posts tonen
Posts tonen met het label SQL. Alle posts tonen

9 jul 2012

do a search in each column of a database


the TSQL code works for me.
But i wonder if there is a more efficient way to do this.
use < DATABASENAME >
declare @ColumnName    varchar ( MAX )
declare @TableName    varchar ( MAX )
declare @GuidToSEarch    varchar ( MAX )


SET @GuidToSEarch = '96E897D-61C7-E911-ECBA-02EA4E855FBE'

declare c1 cursor
for
  -- START OF QUERY TO SEARCH ALL COLUMNS OF DB
SELECT
    SysObjects .[Name] as TableName,
    SysColumns .[Name] as ColumnName
    --SysTypes.[Name] As DataType,
    --SysColumns.[Length] As Length
FROM
   SysObjects INNER JOIN SysColumns
    ON SysObjects .[Id] = SysColumns . [Id]
    INNER JOIN SysTypes
    ON SysTypes .[xtype] = SysColumns . [xtype]
WHERE
    SysObjects .[type] = 'U' AND SysTypes .[Name] != 'sysname'
   and  SysTypes .[Name] = 'uniqueidentifier'
    group by    SysObjects. [Name] , SysColumns .[Name]
ORDER BY
   SysObjects. [Name] , SysColumns .[Name]
 -- END OF QUERY


  open c1
  fetch next from c1 into @TableName , @ColumnName

  while @@fetch_status = 0
  begin     
       exec ( 'SELECT * FROM ' + @TableName + ' where ' + @ColumnName + '=''' + @GuidToSEarch  + '''' )
       if (@@ROWCOUNT =1 )
       BEGIN

       print 'found in ' + @TableName
       -- close c1
        break ;
       END
       fetch next from c1 into @TableName, @ColumnName
  end

  close c1
  deallocate c1
  go

14 feb 2012

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

ADVANCED VERSION WITH GENERATING THE RIGHT DELETE STATEMENTS



BEGIN
-- The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__". The conflict occurred in database "", table "", column ''.
-- THIS SCRIPT DOESNT EXECUTE DELETE STATEMENTS IT ONLY GENERATES THE SQL STATEMENTS

declare @Subtable as nvarchar(100), @roottable as nvarchar(100),  @idColumn as nvarchar(100)

set @Subtable=''
set @Roottable=''
set @idColumn=''

declare @SQLStatement as nvarchar(MAX) , @SQLStatement1 as nvarchar(MAX) ,@SQLStatement2 as nvarchar(MAX) ,@SQLStatement3 as nvarchar(MAX) ,
 @orderstat as nvarchar(MAX) ,  @wherestat as nvarchar(MAX)
SET @orderstat = ' ORDER BY ' + @idColumn
SET @SQLStatement = 'SELECT TOP 1 @ItemId = ' + @idColumn + ' FROM ' + @Subtable + ' as st ' + ' where not exists(select *  from ' + @Roottable + ' as rt where st.' + @idColumn + '=rt.' + @idColumn + ')and ' + @idColumn + ' is not null'
SET @SQLStatement2 = 'SELECT TOP 1 ' + @idColumn + ' FROM ' + @Subtable + ' as st ' + ' where not exists(select *  from ' + @Roottable + ' as rt where st.' + @idColumn + '=rt.' + @idColumn + ')and ' + @idColumn + ' is not null'
SET @SQLStatement3 = ' '' DELETE FROM ' + @Subtable + ' WHERE ' + @idColumn + '= '' + CONVERT(NVARCHAR(10),@ItemId) '
SET @SQLStatement1 = '
BEGIN
Declare @ItemId bigint
 ' + @SQLStatement + @orderstat + '
 PRINT ' + @SQLStatement3 + '
  WHILE @ItemId is not null 
  BEGIN
     if exists (' + @SQLStatement2 + '   AND   ' + @idColumn + '>@ItemId '+ @orderstat + ')
                  begin                                                       
                        ' + @SQLStatement + '  and ' + @idColumn + '>@ItemId  '+ @orderstat + '
                        PRINT ' + @SQLStatement3 + '
                  end
                  else
                  begin
                        set @ItemId=null
                  end
  END
END' 

exec sp_executesql @SQLStatement1
END

DELETE ALL THE CONTENT OF A DATABASE

 Cannot truncate table '' because it is being referenced by a FOREIGN KEY constraint.


EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'   
EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL'   
EXEC sp_MSForEachTable 'DELETE FROM ?'
--EXEC sp_MSForEachTable 'TRUNCATE TABLE ?
-- You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint;
-- instead, use DELETE statement without a WHERE clause.
-- Because TRUNCATE TABLE is not logged, it cannot activate a trigger."
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'   
EXEC sp_MSForEachTable 'ALTER TABLE ? ENABLE TRIGGER ALL'
-- reseed identity columns
EXEC sp_MSForEachTable '
    IF OBJECTPROPERTY(object_id(''?''), ''TableHasIdentity'') = 1
    DBCC CHECKIDENT (''?'', RESEED, 0)'

30 jan 2012

Find rows with constraint errors

BEGIN
declare @Subtable as nvarchar(100), @roottable as nvarchar(100),  @idColumn as nvarchar(100) , @SQLStatement as nvarchar(MAX)
set @Subtable='[table that uses id from source table]'
set @Roottable='[source table]'
set @idColumn='[idColumnName]'
SET @SQLStatement = 'SELECT * FROM ' + @Subtable + ' as st ' + ' where not exists(select *  from ' + @Roottable + ' as rt where st.' + @idColumn + '=rt.' + @idColumn + ')and ' + @idColumn + ' is not null'
PRINT @SQLStatement
exec sp_executesql @SQLStatement
END

Execute stored procedureForEachRow

-- =============================================
-- Author:        elconomeno
-- Create date:
-- Description:   
-- =============================================
CREATE PROCEDURE [dbo].[ExeCuteStoredProcedureForEachRow]

AS
BEGIN
declare @ParameterOfStoredPRocedureToExecute1 varchar(255)
declare cur cursor
for select ColumnWithPArameterValue
from TblToReadFrom -- or from dbo.MyTableFunction()

open cur
fetch next from cur into @ParameterOfStoredPRocedureToExecute1
while @@fetch_status = 0
begin
exec [dbo].[StoredProcedureToExecute] @ParameterOfStoredPRocedureToExecute1
fetch next from cur into @ParameterOfStoredPRocedureToExecute1

end
END

26 jan 2012

find dependent objects from sql table

BEGIN
set @Tablename= 'tablename'
declare @tablename as nvarchar(max)
Select Distinct
o.Name 'TableName',
op.Name 'DependentObject',
op.XType 'objecttype'
From SysObjects o
INNER Join SysDepends d ON d.DepId = o.Id
INNER Join SysObjects op on op.Id = d.Id
Where o.XType = 'U' and o.Name= @Tablename
END

19 jan 2012

input in database from csv file

BULK
INSERT YourTableName

FROM 'C:\Your.csv'

WITH
(
FIELDTERMINATOR = ';',

ROWTERMINATOR = '\n'

)
GO

11 jan 2012

trigger to update timestamp in an sql table

USE [DatabaseName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[updateLastEditTime]
ON [dbo].[LogonLog]
FOR UPDATE, INSERT
AS
UPDATE LogonLog SET [timestamp] = CURRENT_TIMESTAMP 
FROM LogonLog Inner Join Inserted On
LogonLog.username = Inserted.username
and LogonLog.computername  = Inserted.computername