« Newer Snippets
Older Snippets »
15 total  XML / RSS feed 

MS SQL shrink log files for all databases


Truncates and shrinks log files for each user database on MS Sql server.

declare @ssql nvarchar(4000)
set @ssql= '
        if ''?'' not in (''tempdb'',''master'',''model'',''msdb'') begin
        use [?]
        declare @tsql nvarchar(4000) set @tsql = ''''
        declare @iLogFile int
        declare LogFiles cursor for
        select fileid from sysfiles where  status & 0x40 = 0x40
        open LogFiles
        fetch next from LogFiles into @iLogFile
        while @@fetch_status = 0
        begin
          set @tsql = @tsql + ''DBCC SHRINKFILE(''+cast(@iLogFile as varchar(5))+'', 1) ''
          fetch next from LogFiles into @iLogFile
        end
        set @tsql = @tsql + '' BACKUP LOG [?] WITH TRUNCATE_ONLY '' + @tsql
        --print @tsql
        exec(@tsql)
        close LogFiles
        DEALLOCATE LogFiles
        end'

exec sp_msforeachdb @ssql

firebird auto increment trigger

This is a trigger to implement auto-increment/identity columns in Firebird. Another version is using a stored procedure to
get the value of the generator before inserting it then returning the saved generator value. This is needed because Firebird
generators are outside transaction control so reading the generator value again after using it may yield a different number
because it has already been used in a different transaction.

CREATE GENERATOR testgen;

SET TERM $$ ;
CREATE TRIGGER trg_gen_test FOR test_table
ACTIVE
BEFORE INSERT AS
BEGIN
  new.identity_column = gen_id(testgen, 1);
END $$
SET TERM ; $$


SET TERM $$ ;

CREATE PROCEDURE proc_insert ( val1 VARCHAR(20), val2 VARCHAR(20) ) RETURNS 
(generated_id INTEGER)
AS
BEGIN
  generated_id = gen_id(testgen, 1);
  INSERT INTO test_table (identity_column, col1, col2) VALUES (:generated_id, :val1, :val2);
  SUSPEND;
END $$

SET TERM ; $$

/* call the above procedure like this from code (PHP):
SELECT generated_id FROM proc_insert('a', 'b');
of course you can prepare and use placeholders/bind params for the proc parameters
*/

backup multiple mysql databases and email results

// remember to check that the path is correct.
// This is running on a dedicated server on TextDrive

#!/bin/sh

# This file will run a backup of your desired MySQL database and
# remove any backups older than 7 days.
#
# If youOd like to preserve backups for longer than a week, like say 
# 2 weeks, then set the '-mtime' value from '+7' to '+14'.
#

TIME_STAMP=`date "+%Y-%m-%d"`
echo "starting "$0" on" `date`
for db in db1 db2 db3
do
  DB_STAMP=${db}_${TIME_STAMP}
  echo ${DB_STAMP}
  /opt/csw/mysql5/bin/mysqldump --opt --skip-add-locks --user=username --password=password ${db} | gzip > /domains/backups/mysql/${DB_STAMP}.gz
  /opt/csw/bin/mutt -s "mysql  ${TIME_STAMP}"  -a /domains/backups/mysql/${DB_STAMP}.gz someuser@somedomain.com dev/null
done

cd /domains/backups/mysql/

/usr/bin/find *.gz -mtime +14 -exec rm {} \;
echo "finished "$0" on" `date`

ReSeed Table

// this resets the seed to whatever you want.... change XXX to the new seed

DBCC CHECKIDENT (CustomerContactType, RESEED, XXX)

Reset Error AutoFile

// description of your code here

update orders set statusid = 1,currentqueueid = 1, ntuser = null,checkedout = null where orderid = 19111067

Get Efile Counts

// description of your code here

select
        convert(varchar(6),n.notedate) as [date],count(*) as cnt
into
        #temp
from
        orders o inner join 
        orderdetail od on o.orderid = od.orderid inner join
        ordernotes n on o.orderid = n.orderid
where
        od.jurisdictionid = 3152 and
        od.serviceid in (3,4,12,13,15,18) and
        (n.noteid = 129 and n.notedate > '4/1/2006 12:01 AM')
group by
        convert(varchar(6),n.notedate)
order by
        convert(varchar(6),n.notedate)

select * from #temp
compute sum(cnt)
drop table #temp

Get column names from MSSQL

SELECT table_name=sysobjects.name,
         column_name=syscolumns.name,
         datatype=systypes.name,
         length=syscolumns.length
    FROM sysobjects 
    JOIN syscolumns ON sysobjects.id = syscolumns.id
    JOIN systypes ON syscolumns.xtype=systypes.xtype
   WHERE sysobjects.xtype='U'
ORDER BY sysobjects.name,syscolumns.colid

find duplicates

SELECT column,COUNT(*) c FROM table
GROUP BY column HAVING COUNT(*) > 1

results show the column value and the number of duplicates for that value

Dynamic ordering without dynamic sql

DECLARE @order int
SET @order = 1
SELECT * FROM users
ORDER BY 
        CASE WHEN @order = 1 THEN [name] END DESC,
        CASE WHEN @order = 2 THEN [name] END ASC,
        CASE WHEN @order = 3 THEN [email] END DESC,
        CASE WHEN @order = 4 THEN [email] END ASC

set the @order to 1-4 to get specific order by clause, setting it to anything else give results as if no order by clause supplied

remember dynamic SQL (creating SQL in a string and then executing) can not be effectively cached so this is a much better option

Randomly ordered results in TSQL

SELECT TOP 10 userID
FROM user
ORDER BY NEWID()

or
SELECT TOP 10
        NEWID() [egg],
        userID
FROM user
ORDER BY [egg]

or
SELECT TOP 10
        NEWID(),
        userID
FROM user
ORDER BY 1

only tried the above with TSQL

SQL UPDATE FROM example

UPDATE emailFormat 
SET format=2 
FROM emailFormat EF
INNER JOIN user U ON EF.userID = U.userID 

I have seen people use temporay tables and loops to do this sort of thing in the past

UDF to add a sql_variant to a list

--Adds a sql_variant element to the end of a sql_variant list, after first inserting a delimiter (nvarchar)
--If both element and list are nvarchars, using dbo.fnAddToList will be faster
ALTER FUNCTION dbo.fnAddVarToList (@VarList sql_variant, @VarNew sql_variant, @Del nvarchar(10))
RETURNS nvarchar(4000)
AS  
BEGIN 
        DECLARE @List nvarchar(4000), @New nvarchar(4000)
        SELECT @List = NULLIF(CONVERT(nvarchar(4000), @VarList), ''), 
                @New = NULLIF(CONVERT(nvarchar(4000), @VarNew), '')
        --First try the concatened string, if null then just the list, 
        --if it too is null, just the new element
        RETURN COALESCE(@List + @Del + @New, @List, @New)
END

UDF to add items to a list, specifying the delimiter

--Adds an element (nvarchar) to the end of a list (nvarchar), after first inserting a delimiter (nvarchar)
ALTER FUNCTION dbo.fnAddToList (@List nvarchar(4000), @New nvarchar(4000), @Del nvarchar(10))
RETURNS nvarchar(4000)
AS  
BEGIN 
        --Treat ''s as NULLs
        SELECT @List = NULLIF(@List, ''), @Del = NULLIF(@Del, ''), @New = NULLIF(@New, '')
        --First try the concatened string, if null then just the list, 
        --if it too is null, just the new element
        RETURN COALESCE(@List + @Del + @New, @List, @New)
END

UDF to Add items to a comma delimited list

/*
_A_dd to _C_omma delimited _L_ist - simplified version of AddToList
Adds an element (nvarchar) to the end of a comma delimited list (nvarchar)
*/
ALTER FUNCTION dbo.fnACL (@List nvarchar(4000), @New nvarchar(4000))
RETURNS nvarchar(4000)
AS  
BEGIN 
        --Treat ''s as NULLs
        SELECT @List = NULLIF(@List, ''), @New = NULLIF(@New, '')
        --first try returning the concatened string, if null then try just the list, if it too is null, just the new element
        RETURN COALESCE(@List + ',' + @New, @List, @New)
END

A query from ActiveRecord that isn't working

SELECT
t.*, j.* FROM terms_values j, values t WHERE t.id = j.value_id AND j.term_id = 310
« Newer Snippets
Older Snippets »
15 total  XML / RSS feed