MSSQL – Simple Fuzzy String Match.

 

Sometimes we need to get a little creative with our querying. Having some nice, helpful functions on hand can be a great help and a fabulous time saver.  Here is one from our collection that has been useful on a surprising number of occasions.

So what does it do?

Basically it returns true if a certain amount of consecutive string characters contained in any part of @Str1 matches any part of @Str2. The length of the match is controlled be the @Precision parameter.

It is useful where your want to find strings that are similar but not exactly the same.

With a little extra code using the inbuilt TSQL function "SoundEx" this could easily become an extremely powerful word analyser.

In it's current form it could even be used to search for documents with similar phrasing.

Anyway, we hope you find it a useful function to add to your ever expanding TSQL tool belt.

Enjoy.

 

SET ANSI_NULLS ON

 

GO

SET QUOTED_IDENTIFIER ON

GO

– =============================================

– Author:      Proficient IT (http://www.proficientit.com.au)

– Create date: 04/01/2011

– Description: Match two strings if any part of the string of length set by presistion matches the next.

– =============================================

CREATE FUNCTION fn_FuzzyStringMatch

(

     @Str1 Nvarchar(4000)

     , @Str2 Nvarchar(4000)

     , @Precision int = 4

)

RETURNS bit

AS

BEGIN

 

     DECLARE @Str1Len int SET @Str1Len = LEN(@Str1)

     DECLARE @MaxPosition int SET @MaxPosition = @Str1Len - @Precision

     DECLARE @Str1Extract Nvarchar(4000)

 

     DECLARE @i int = 1

     WHILE @i <= @MaxPosition BEGIN

           SET @Str1Extract = SUBSTRING(@Str1, @i, @Precision)

 

           IF @Str2 LIKE '%' + @Str1Extract + '%' BEGIN

                RETURN 1

           END

 

           SET @i = @i + 1

     END

 

     RETURN 0

 

END

GO

 

 

Related Posts:

Posted in Uncategorized | Tagged , , | Leave a comment

MSSQL – Simple Live backup


 
This is not a Live backup in the sense of transaction level replication but simply a snapshot in time of a database already mounted and ready to be queried.

A very simple way to have a live backup is to use a script to backup an existing live database and automatically restore the backup as a new or existing database.
If this is done as a SQL Server Agent job then it can be executed as often as needed giving you a live snapshot of a database which can be queried as if it were the real thing.
I generally do not use this method as a true backup and would not recommend doing so. Although, I have found it very useful in keeping development and debugging databases as up to date as possible. This means that developers do not need to worry that they are working on an old version of the database just because no one bothered to update it.
In the sense of an update it can often be helpful to have a live version of the current production data from 30 minutes or so ago. Trust me, as a database admin you soon realize how easy it is to make a typo or somebody comes along and bothers you and you forget a WHERE clause on your UPDATE statement. While, for me anyway, this a rarity the live backup can help you quickly get the database back up and running.
Anyway here is the script I have been using to do the task;
 
 
Warning: When you edit this script to work for your database make sure you get the database names the correct way round. Otherwise this could wipe your original database. Do not attempt this unless you know what you are doing.

USE master
–create myDatabase back file
BACKUP DATABASE [myDatabase]TO DISK = N'C:\temp\myDatabase.sql.bak'
WITH RETAINDAYS = 7, FORMAT, INIT, NAME = N'myDatabase Full Database Backup'
, SKIP
, NOREWIND
, NOUNLOAD
, STATS = 10GO

IF DB_ID('myDatabase_live_backup') IS NOT NULL BEGIN

      DECLARE @spid INT

      DECLARE @sql NVARCHAR(100)
      DECLARE csurProcess CURSOR FOR
            SELECT SPID
            FROM master..sysprocesses pr
            INNER JOIN sys.databases da ON pr.dbid = da.database_id
            WHERE da.name = 'myDatabase_live_backup'

      OPEN csurProcess
      FETCH NEXT FROM csurProcess INTO @spid WHILE @@FETCH_STATUS = 0 BEGIN

            PRINT 'Killing process ' + CONVERT(NVARCHAR, @spid) + '.'
            SET @sql = 'KILL ' + CONVERT(NVARCHAR, @spid)
            EXEC(@sql)

            FETCH NEXT FROM csurProcess INTO @spid
      END

      CLOSE csurProcess
      DEALLOCATE csurProcess

END ELSE BEGIN

      CREATE DATABASE myDatabase_live_backup

END
GO
ALTER DATABASE [myDatabase_live_backup]
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
–Retore myDatabase backup to myDatabase_live_backup
RESTORE DATABASE [myDatabase_live_backup] FROM DISK = N'C:\Temp\myDatabase.sql.bak'WITH FILE = 1,
MOVE N'myDatabase' TO N'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\myDatabase_live_backup.mdf'
, MOVE N'myDatabase_log' TO N'C:\Program Files\Microsoft SQL
Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\myDatabase_live_backup.ldf'
, NOUNLOAD
, REPLACE
, STATS = 10GO

ALTER DATABASE [myDatabase_live_backup]SET MULTI_USER WITH ROLLBACK IMMEDIATE;

Related Posts:

Posted in Uncategorized | Tagged , , , , , , , | 4 Comments

ASP.NET – Disable saving of password / user name.

 

Trying to stop people saving their login details on public computers? Often it is done inadvertently by people forgetting to un-tick a “Remember me” or “Keep me logged in”. Although this is only available on sites that give the option. Even if a site doesn’t offer this function, almost all modern browsers will offer to save the password anyway.

To stop this you can simply add the following line to you page load event;

form1.Attributes.Add(“autocomplete”, “off”);

If you are using a master page you can add this to the master page code behind. Remember though if you do it this way then it will stop any text on all your pages to not remember anything when the user come back to the page. This can actually become annoying so only use it when necessary.

Another method is to change the property of the textbox, of the username and password controls, “AutoCompleteType” to “Disable“.

You may need to change both the password textbox and the username textbox properties to “Disabled” in order for this to work as most browsers use the selection of a past username as the trigger point to save/retrieve the password.

The benefit of the second method is that it only affects the targeted fields.

I have not tested this on all browsers. It has worked on IE7, IE8, Safari, Firefox and Chrome.

Enjoy.

Related Posts:

  • No Related Posts
Posted in Uncategorized | Tagged , | Leave a comment

Kill processes in SQL server from TSQL.

 

Sometimes you need to kill processes in SQL. I find that when I need to restore a database in I get that annoying “Cannot get exclusive access” error. One way to do it would be to run the command;
 
ALTER DATABASE [TestDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
 
I find this a little harsh as I can do some real damage in a hurry if I muck it up. Not only the database I am dealing with but the whole server.
 
I prefer just killing or the processes relating to the database and then working on it immediately afterward.
 
Killing the processes in the GUI can become a little tedious though so I wrote a quick script (below) to do the leg work for me.
 
Now if a want to kill all processes relating to a database I simply pass the database name into my script (without passing a user name) and bang, they are all dead.
 
I ended up adding the login parameter because although I have not yet used it I can think of reasons in the future where it may come in handy. Say for instance, a rogue user is hogging all the server resources I can knock them out in a single punch. Obviously I am an admin though.
 
To see which login is using the most resources directly from TSQL use this query (SQL 2005,2008+);
 
SELECT pr.loginame
, COUNT(*) Processes
, SUM(pr.cpu) cpu
, SUM(pr.physical_io) physical_io
, SUM(pr.memusage) memusage
FROM master..sysprocesses pr
GROUP BY pr.loginame
ORDER BY SUM(pr.cpu) DESC, pr.loginame
 
The script (SQL 2005,2008+);
 
–KILL SQL PROCESSES
–proficientit.com.au
 
–Note passing nothing kills all processes except the current one.
–Passing only @dbName name will kill all processes for that database.
–Passing only @loginName name will kill all processes for that login.
 
DECLARE @dbName As Nvarchar(50) = 'DB_NAME' –Database name
DECLARE @loginName AS Nvarchar(50) = 'MY_DOMAIN\MY_USER' –'MY_DOMAIN\MY_USER' or 'SQL_USER', basically how it appears in Security/Logins
 
USE master
 
IF @dbName IN('master','model','msdb','tempdb') BEGIN RAISERROR('This script can only kill user processes.',16,1) RETURN END
IF ISNULL(@dbName,'') <> '' AND DB_ID(@dbName) IS NULL BEGIN RAISERROR('Database does not exist or you don''t have permission to see it.',16,1) RETURN END
IF ISNULL(@loginName,'') <> '' AND NOT EXISTS(SELECT name FROM master.dbo.syslogins WHEREname = @loginName) BEGIN RAISERROR('Login doesn''t exist on this server or you don''t have permission to see it.',16,1) RETURN END
 
DECLARE @spid INT
     DECLARE @sql Nvarchar(100)
     DECLARE csurProcess CURSOR FOR
           SELECT pr.SPID
           FROM master..sysprocesses pr
           INNER JOIN sys.databases da ON pr.dbid = da.database_id
           WHERE (da.name = @dbName OR ISNULL(@dbName,'') = '')
           AND (pr.loginame = @loginName OR ISNULL(@loginName,'') = '')
           AND pr.SPID <> @@SPID –Can't kill this session(this script is running in it).
     OPEN csurProcess
     FETCH NEXT FROM csurProcess INTO @spid WHILE @@FETCH_STATUS = 0 BEGIN
           PRINT 'Killing process ' + CONVERT(NVARCHAR, @spid) + '.'
           SET @sql = 'KILL ' + CONVERT(NVARCHAR, @spid)
           EXEC(@sql)
           FETCH NEXT FROM csurProcess INTO @spid
     END
     CLOSE csurProcess
     DEALLOCATE csurProcess
 
–See what processes are current active.
SELECT pr.SPID, da.name [dbName], pr.loginame
, pr.cpu, pr.physical_io, pr.memusage, pr.login_time, pr.last_batch
FROM master..sysprocesses pr
INNER JOIN sys.databases da ON pr.dbid = da.database_id
 
 Enjoy.

Related Posts:

Posted in Uncategorized | Tagged , , , , | Leave a comment

Turning Google into a file sharing service.

 

There is so much out there on the internet. So many shared directories, some of which may or may not have been shared on purpose, some are shared by people who simply don’t understand that on the internet, anybody can see it.
 
The great thing is that one of those any bodies is Google. The trick is to find it. There are many different ways to search Google and you can do some very intense searching but some of these search terms would literally take 2 minutes just to type in.
 
So to the rescue I have created this JavaScript shortcut to help find files on the internet.
 
Simply create a shortcut in your favourite browser (only tested in Firefox and mainly Google Chrome) and paste the below text into the address bar. Name it File Search. Previously seemed to work in IE but no longer seems to allow the javascript dialogue box.
 
Next just click the shortcut. Enter any file extentions you want searched separated by the “|” symbol. Then enter part of the filename you are searching for. It will then use Google to search web directories of file shares.
 
Hopefully you will find what you are looking for. Remember some people like to bait Google and make sites that appear to be web directories but are just rude. Hopefully Google’s algorithms will get better and filter these out. Actually that goes for all Google searches.
 
The shortcut:
Copy all of the following text into a new internet shortcut in your browser. Exactly as it is.
 
javascript:var ext=prompt("Please enter file extensions separated by |.","mp3");var srh=prompt("Please search term.","");window.location = "http://www.google.com/search?&q=-inurl:(htm|html|php) intitle:\"index of\" +\"last modified\" +\"parent directory\" +description +size +(" + ext + ") \"" + srh + "\"";
 
 
Enjoy.

Related Posts:

  • No Related Posts
Posted in Uncategorized | Tagged , | Leave a comment

Script user permissions in SQL for server migration.

This script is a great help when you need to move a database to a different server as it dramatically speeds up the process and leaves a lot less room for errors compared with doing the process by hand. I can’t count how many times I have used this script.

The reason for needing the script is that even when you create a new SQL login by the same name on the new server, when you restore or attach the existing database the database user does not map the the new login. Even though they have the same name they have different identifiers.

The best approach is to prepare the move by running the below script on the database in it’s existing location. This will then generate a new script that you save for later use. Do this for all necessary database users.

Next restore/attach the database in it’s new location and delete the users from the database. Yes I said delete them.

Now run the scripts you generated at the start and it will recreate the Logins and map all the role and permissions from the last server. If you have multiple scripts for multiple users run them all sequentially.

Sometimes the script has an issue creating the actually server login. If it does create logins yourself by the same names. The password can be set to what ever you need. Also in the generated script you may need to comment out the part at the top that creates the login to prevent an error.

The script is written by Bradley Morris back in 2002 and I have had no problems, even today, using it on SQL Server 2008.

Find the script here.
http://www.sql-server-performance.com/articles/dba/object_permission_scripts_p1.aspx

Enjoy.

Related Posts:

  • No Related Posts
Posted in Uncategorized | Leave a comment

Deleting a Facebook account.

A very common question I get is “How do I delete my Facebook account?” Weird thing is, facebook wont tell you. Legally they want to give you the tools to do it, so they can say we have free will, but morally they want your details stuck with them, own by them, for life.

Even once you have successfully deleted an account any activity on the account will re-create the account.

Well, luckily someone has gone to the effort to let us know how. Read this interesting post. Why does Facebook make it so hard to leave. Do they know something we dont know?

Read it. Get rid of Facebook.

Is it because so may people are leaving, disgusted with how Facebook turned out. They joined just to see what was the fuss. They stayed just to see what changed. Perusing around trying to see who is doing what but all the while missing out on events due to the fact they where too busy looking and drooling over what everyone else was doing. On the the internet. Forgeting that there is is a real life outside of Facebook.

Facebook says it has reached 500 million users but how many of these users simply can’t delete their account?

So and so said so and so to so and so. Who cares you say? If I had no Facebook then my life would be simpler. I would be worrying about real events and getting further in my life.

Facebook is a diversion. Get on with life.

Related Posts:

  • No Related Posts
Posted in Uncategorized | Leave a comment

Backup your hard drive over the network with dd and ssh

Came across this enlightening post about how to backup and restore a system using a Linux boot disk and a separate Linux box as a storage device.

Hope you find as useful as I have.

http://www.pantz.org/software/dd/drivecopywithsshanddd.html

Related Posts:

  • No Related Posts
Posted in Uncategorized | Leave a comment

Using global variables inside PHP functions

Within a function normal variable reference in the scope of the PHP file cannot be directly referenced. This is not a weakness of PHP but a feature meant to save programmers from themselves. Any variable that is to exist inside of a function must have the express permission of the programmer. The protection this provides is that the programmer cannot accidentally or inadvertently create a variable by the same name as a variable inside a function creating unknown havoc.

Therefore, if you want to use any value inside of a PHP function that does originate from inside the function itself there are two ways to go about it.

The most simple and most would argue correct is to enter the variable as an input parameter of the function itself.

For example;

<?php

function myFunction($myVariable){

echo $myVariable;

}

myFunction(“myVariableValue”);

?>

While simple and correct, it is not always what you want. If you are writing functions that are using the same variables over and over it just doesn’t make sense as a human to have to input the same information into multiple functions. One example is if you have a large number of functions that need the sites global connection string passed into everyone.

In this case you can allow your function to access the external variable using the global statement.

For example;

<?php

function myFunction() {

global $myVariable;

echo $myVariable;

}

$myVariable = “myVariableValue”;

myFunction ();

?>

As you can see we have given explicit permission for the function to access data from the variable that was set outside the scope of the function.

I would recommend that you limit your usage of the global statement to variables that are unique and used extensively throughout your project. Things like a global database connection strings and similar would be acceptable. Outside this I would strongly recommend using function input parameters only. This will help keep your code clean and understandable for when someone else needs to look at your code or even when you yourself need to come back in the future and make a change. Another reason is that if you reuse your function in another project you rule out any chance of cross variable contamination.

Related Posts:

  • No Related Posts
Posted in Uncategorized | Tagged , , , | Leave a comment

MSSQL – Creating a logon trigger

This script will help you setup a database that will log all logins into a MSSQL server. This has only been tested on Windows SQL Server 2008 but it should be ok for 2005 as well.

** WARNING ** Don’t try this on your production server until you are feeling very comfortable about it. If you make a mistake and cause the trigger to error you may not be able to login. I suggest trying this on a testing server first. Also I always keep at least one query window connected at all times when setting this up. If you do happen to lock yourself out try this great post http://www.codeproject.com/Tips/82007/SQL-Server-Logon-Triggers-Trouble.aspx.

The Script 

USE master

GO
–CREATE OUR NEW DATABASE
CREATE DATABASE LoginsDatabase
GO
–OK LETS USE IT
USE LoginsDatabase
GO
–CREATE A LOGIN IN WHICH TO EXECUTE OUR TRIGGER AS
CREATE LOGIN LOG_USER WITH PASSWORD=N’LOG_u$er_01′, DEFAULT_DATABASE=LoginsDatabase
GO
–CREATE A USER FOR CURRENT DATABASE WHICH IS NOW LoginsDatabase
CREATE USER LOG_USER FOR LOGIN LOG_USER
GO
–GRANT READ/WRITE PERMISSIONS TO OUR NEW USER
EXEC sp_addrolemember N’db_datareader’, N’LOG_USER’
GO
EXEC sp_addrolemember N’db_datawriter’, N’LOG_USER’
GO
–CREATE A TABLE TO HOLD OUR LOGIN DATA
CREATE TABLE [ServerLogins](
ID bigint IDENTITY(1,1) NOT NULL
, [EVENTDATA] xml NOT NULL
) ON [PRIMARY]
GO
–CREATE OUR NEW TRIGGER THAT WILL RUN AS LOG_USER
CREATE TRIGGER logon_trigger_login_log
ON ALL SERVER WITH EXECUTE AS ‘LOG_USER’
FOR LOGON–DDL_LOGIN_EVENTS
AS
INSERT INTO LoginsDatabase.dbo.ServerLogins([EVENTDATA]) VALUES (EVENTDATA())
GO
–LOGIN IN AND OUT OF THE DATABASE AS SOMEONE TO GENERATE DATA.
–RUN SELECT TO SEE WHAT WE HAVE RECORDED.
SELECT *
FROM LoginsDatabase.dbo.ServerLogins
–EXAMPLE OUTPUT
–   <EVENT_INSTANCE>
–         <EventType>LOGON</EventType>
–         <PostTime>2010-08-12T22:33:14.677</PostTime>
–         <SPID>58</SPID>
–         <ServerName>machine_name</ServerName>
–         <LoginName>LOG_USER</LoginName>
–         <LoginType>SQL Login</LoginType>
–         <SID>eudUx3DfyESj/8yCaF2PpA==</SID>
–         <ClientHost>&lt;local machine&gt;</ClientHost>
–         <IsPooled>0</IsPooled>
–   </EVENT_INSTANCE>

Related Posts:

Posted in Uncategorized | Tagged , | Leave a comment