Blog Archives
Cannot login logon failed to SQL Server Windows Auth
Locked out of SQL Server? Accidentally right click on your account in Management Studio and hit delete? Or did Sys Admins force you onto the domain and delete your local superman account that you installed SQL under? Oops! No problem! (If You’re a local admin).
Check out these simple steps.
First, run a cmd prompt as administrator. Enter the following. This will start sql in single user mode, enable the built in sa account, and reset the password for it.
net stop mssqlserver net start mssqlserver /c /m /t3604 sqlcmd -E alter login sa with password='1234' go alter login sa enable go exit net stop mssqlserver
Now open your registry (regedt32) and browse to:
HKLM\Software\Microsoft\Microsoft SQL Server\(Find Your Instance)\MSSQLServer\LoginMode
Change the value to 2. Then go back to command prompt and enter:
net start mssqlserver
Voila! You’re back in business. Fire up management studio and enter your instance name and the sa credentials you created, don’t forget to select sql server authentication.
Once you’re in, Microsoft recommends changing back to Windows Auth (adding your domain/local account). This is up to you. Enjoy.
Arithmetic overflow error converting type to data type numeric
This error usually occurs when the type you are trying to convert to a decimal or numeric is larger than the column or casted type you are converting to.
Ex.
insert into tablename (decnumber) values (cast(1000.00 as decimal(5,2)))
Since the number specifed is 7 digits long include after the decimal and the converted type can only contain a maximum of 5 digits, you will receive this error.
Changing the table to hold 7,2 and/or changing this in the cast will resolve it.
References
devshed (forums), http://forums.devshed.com/ms-sql-development-95/arithmetic-overflow-error-converting-numeric-to-data-type-numeric-89157.html
DLL in Stored Procedure MSSQL
Extended Stored Procedures (MSDN), http://support.microsoft.com/kb/190987
Thread Local Storage in an extended stored procedure (MSDN), http://support.microsoft.com/kb/163449
C# MySQL On Windows Named Pipes Development Mode
While outlining the scope for a new project I’ve considered the possibility of using MySQL for budgeting purposes with respect to the potential size and growth rate of the database.
I downloaded and ran through the latest setup for MySQL on Windows (x64 although I opted for the 32 bit binaries) and popped in the MySql Connector DLL (ADO not ODBC) into my project and began whipping up some code in no time.
However, this little trick seemed to be not well known after some google searching on why MySQL Workbench (great tool btw) can connect, but my app could not.
Being a security conscious developer, when installing SQL I selected developer mode and opted for a safer named pipes connection for local development vs socket network connection looping through my localhost via TCP.
If you also selected this option, you may have had trouble getting your app to connect as well.
After searching through various (not necessarily directly related) sites, I found the answer.
See simple connection string snippet below.
Pipe=MySQL;Protocol=pipe;Host=.;Database=[yourdb];User ID=[youruser];Password=[yourpass]
To my surprise, the little note about specifying a period “.” as the host for named pipe connections was not easily found in the references below..
References
PhalangerMySQL (Java2s), https://www.java2s.com/Open-Source/CSharp/Database/PhalangerMySQL/MySql/Data/CatalogData.htm
.Net MySQL Connector Documentation (MySql), http://dev.mysql.com/doc/refman/5.1/en/connector-net.html
Network Traffic Filter Documentation (wireshark), http://wiki.wireshark.org/DisplayFilters
Connecting MySQL via CLI (MySQL), http://dev.mysql.com/doc/refman/5.1/en/connecting.html
Connection String Reference (MySQL), http://dev.mysql.com/doc/refman/5.1/en/connector-net-connection-options.html
MySQL Workbench Documentation (huihoo), http://docs.huihoo.com/mysql/refman-5.5-en/wb-intro.html
Connectionstrings.com, http://www.connectionstrings.com/mysql
codemaker.co.uk, http://www.codemaker.co.uk/it/tips/ado_conn.htm#MySQLNETNativeProvider
MySqlConnection in C# (bitdaddys)http://bitdaddys.com/MySQL-ConnectorNet.html
PHP MySQL Reference, http://php.net/manual/en/function.mysql-connect.php
MySqlCommand in C# (stackoverflow) http://stackoverflow.com/questions/2775692/c-and-mysql-net-connector-any-way-of-preventing-sql-injection-attacks-in-a-ge
MSSQL Quick Reference
Snippets below have been condensed from their original sources for brevity. See references for original articles.
Great reference on joins: http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

Show all tables in specific database: (MSSQL equivalent of MySql “show tables”)
select name from <database name>..sysobjects where xtype = 'U'
Insert into:
INSERT INTO MusicArtists (FirstName, LastName, Instrument)
VALUES ('Bobby', 'Lee', 'fiddle');
INSERT INTO Duos (Member1)
SELECT FirstName + ' ' + LastName FROM MusicArtists;
INSERT INTO Duos (Member1)
SELECT FirstName + ' ' + LastName FROM MusicArtists
WHERE MusicianID > 3;
INSERT INTO Residents (Name, Occupation)
SELECT Name, Occupation FROM Immigration
WHERE Residency = 'granted';
INSERT INTO Insurance (Name)
SELECT Employee.Username FROM Employee
INNER JOIN Project ON Employee.EmployeeID = Project.EmployeeID
WHERE Project.ProjectName = 'Hardwork';
Insert if not exists:
IF NOT EXISTS (SELECT * FROM dbo.Applications WHERE Username = Tom ANDApplication = Calculator) BEGIN
INSERT INTO dbo.Applications
(Date, Username, Application, Version)
VALUES
('3/10/2009', 'Tom', 'Calculator', '2.0')
END
Trigger Syntax Structure:
CREATE TRIGGER trigger_name
ON { table | view }
[ WITH ENCRYPTION ]
{
{ { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
[ WITH APPEND ]
[ NOT FOR REPLICATION ]
AS
[ { IF UPDATE ( column )
[ { AND | OR } UPDATE ( column ) ]
[ ...n ]
| IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
{ comparison_operator } column_bitmask [ ...n ]
} ]
sql_statement [ ...n ]
}
}
Basic If, Then , Else and case:
--longer create proc sp_generic (@cust int, @type int) if @type = 1 select * from customer where customerid = @cust else Select * from deleted_customers where customerid = @cust --shorter create proc sp_generic (@deptid int ) select * from employees where departmentid = case when @dept >0 then @dept else departmentid end order by departmentid
Insert Trigger:
CREATE TRIGGER trig_addAuthor ON authors FOR INSERT AS -- Get the first and last name of new author DECLARE @newName VARCHAR(100) SELECT @newName = (SELECT au_fName + ' ' + au_lName FROM Inserted) -- Print the name of the new author PRINT 'New author "' + @newName + '" added.'
Update Trigger:
USE AdventureWorks2008R2;
GO
IF EXISTS (SELECT name FROM sys.objects
WHERE name = 'reminder' AND type = 'TR')
DROP TRIGGER Person.reminder;
GO
CREATE TRIGGER reminder
ON Person.Address
AFTER UPDATE
AS
IF ( UPDATE (StateProvinceID) OR UPDATE (PostalCode) )
BEGIN
RAISERROR (50009, 16, 10)
END;
GO
-- Test the trigger.
UPDATE Person.Address
SET PostalCode = 99999
WHERE PostalCode = '12345';
GO
Get and/or compare today’s date:
convert(varchar,CURRENT_TIMESTAMP,101) convert(varchar(12),getdate(),101)
Insert or Update with case statements:
USE [mydatabasename] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[sp_update_manufacturedrobots_count] @mfgid int, @robotid int, @paintbotcount int=null, @drillbotcount int=null, @hammerbotcount int=null AS BEGIN SET NOCOUNT ON; declare @id int select @id = id from manufacturedrobots where mfgid=@mfgid and robotid=@robotid if @id is not null update manufacturedrobots set paintbotcount=case when @paintbotcount is null then paintbotcount else @paintbotcount end, favorite=case when @drillbotcount is null then drillbotcount else @drillbotcount end, checkedin=case when @hammerbotcount is null then hammerbotcount else @hammerbotcount end where id=@id else insert into manufacturedrobots (paintbotcount,drillbotcount,hammerbotcount) values (@paintbotcount,@drillbotcount,@hammerbotcount) END
References:
MSDN, http://msdn.microsoft.com/en-us/library/ms187326.aspx
DevGuru, http://www.devguru.com/technologies/t-sql/7124.asp
DevArticleshttp://www.devarticles.com/c/a/SQL-Server/Using-Triggers-In-MS-SQL-Server/1/
MSDN, “How to debug stored procedures in Visual Studio .NET”, http://support.microsoft.com/kb/316549
CodeGuru, http://www.codeguru.com/forum/showthread.php?t=473102
DaniWeb, http://www.daniweb.com/forums/thread43719.html
Import OData / XML / RSS / Webservice Feeds into Excel
If you came here looking for some quick and easy code that you can plug right in and dump data in excel format.. You have come to the wrong spot.
Depending on the scenario you may need this functionality for, you may want to check out a cool tool backed by Microsoft called “Powerpivot“.
This code is not hard to write, but there are many points of error and re-implementation for multiple users and/or clients is likely a larger project than you (or your boss) might realize if you haven’t dealt with data conversion processes before or have multiple complex data relationships which may or may not change data structure over time (addition/removal of columns, mappings, etc).
(For an example on some sample code to help you with this task, see one of my older entries on converting datatable to csv. http://ronniediaz.com/2010/03/02/csv-to-datatable/)
However, if you decide to go the power pivot route, this is a cool little plugin for use with Microsoft Excel which allows you to directly import data from various streams and feeds including OData and SQL.
This plugin basically eliminates the steps involved for an end user to “export to csv, then import into excel”, as well as cuts back on the time and potentially error prone task of assigning a developer to create a data export for this same process.
Check it out.
http://www.powerpivot.com/