Thursday, July 19, 2012

[MSSQL] Check If Temporary Table Exists

How do you check if a temp table exists?
You can use IF OBJECT_ID('tempdb..#temp') IS NOT NULL
Let's see how it works

--Create table
USE Norhtwind
GO

CREATE TABLE #temp(id INT)

--Check if it existsIF OBJECT_ID('tempdb..#temp') IS NOT NULL
BEGIN
  PRINT '#temp exists!'END
ELSE
BEGIN
  PRINT
'#temp does not exist!'END

--Another way to check with an undocumented optional second parameterIF OBJECT_ID('tempdb..#temp','u') IS NOT NULL
BEGIN
  PRINT '#temp exists!'END
ELSE
BEGIN
  PRINT
'#temp does not exist!'END

--Don't do this because this checks the local DB and will return does not existIF OBJECT_ID('tempdb..#temp','local') IS NOT NULL
BEGIN
PRINT '#temp exists!'END
ELSE
BEGIN
PRINT
'#temp does not exist!'END

--unless you do something like this
USE tempdb
GO

--Now it exists againIF OBJECT_ID('tempdb..#temp','local') IS NOT NULL
BEGIN
  PRINT '#temp exists!'END
ELSE
BEGIN
  PRINT
'#temp does not exist!'END

--let's go back to Norhtwind again
USE Norhtwind
GO

--Check if it existsIF OBJECT_ID('tempdb..#temp') IS NOT NULL
BEGIN
PRINT '#temp exists!'END
ELSE
BEGIN
PRINT
'#temp does not exist!'END

now open a new window from Query Analyzer (CTRL + N) and run this code again
--Check if it existsIF OBJECT_ID('tempdb..#temp') IS NOT NULL
BEGIN
  PRINT '#temp exists!'END
ELSE
BEGIN
  PRINT
'#temp does not exist!'END

It doesn't exist and that is correct since it's a local temp table not a global temp table

Well let's test that statement
--create a global temp table
CREATE TABLE ##temp(id INT) --Notice the 2 pound signs, that's how you create a global variable

--Check if it existsIF OBJECT_ID('tempdb..##temp') IS NOT NULL
BEGIN
  PRINT '##temp exists!'END
ELSE
BEGIN
  PRINT
'##temp does not exist!'END

It exists, right?
Now run the same code in a new Query Analyzer window (CTRL + N)

--Check if it existsIF OBJECT_ID('tempdb..##temp') IS NOT NULL
BEGIN
  PRINT '##temp exists!'END
ELSE
BEGIN
  PRINT
'##temp does not exist!'END

And yes this time it does exist since it's a global table (with ## (double-dash) as a prefix).

Tuesday, July 17, 2012

[MSSQL] Access to the remote server is denied because no login-mapping exists

Problem: Unable to run a query through a linked server SQL Server 2005. This problem only happens with a non-sysadmin account.

You got the message below:
Msg 7416, Level 16, State 2, Line 1
Access to the remote server is denied because no login-mapping exists..


Cause: When creating a linked server with the parameter @provstr and you use a local SQL Server non-admin or non-Windows account, you have to add the parameter "User Name"   into the @provstr

Resolution : Add "User ID=Username" into the provider string on your linked server

EXEC master.dbo.sp_addlinkedserver @server = N'LinkServerName', @provider=N'SQLNCLI',@srvproduct = 'MS SQL Server', @provstr=N'SERVER=serverName\InstanceName;User ID=myUser'
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname = N'LinkServerName', @locallogin = NULL , @useself = N'False', @rmtuser = N'myUser', @rmtpassword = N'*****'

Check:
SELECT  TOP 1 * FROM LinkServerName.msdb.dbo.backupset
GO
SELECT * FROM OPENQUERY (LinkServerName, 'SELECT TOP 1 * FROM msdb.dbo.backupset ')

Monday, July 2, 2012

[EXCEL] How to count the occurrences of a number or text in a range in Excel

How to Count the Occurrences of a Number

Use this formula
=SUM(IF(range=number,1,0))
where range is the range that you want to search, and number is the number that you want to count.

NOTE: This formula must be entered as an array formula. To enter an array formula, press CTRL+SHIFT+ENTER.

How to Count the Occurrences of a Text String

Method 1

Use this formula
=SUM(IF(range="text",1,0))
where range is the range that you want to search, and text is the text that you want to find (the text must be enclosed in quotation marks).

NOTE: The above formula must be entered as an array formula. To enter an array formula, press CTRL+SHIFT+ENTER.

Method 2

Use the COUNTIF() function to count the occurrences of a text string. For example, use the formula
=COUNTIF(range,"text")
where range is the range of cells that you are evaluating, and text is the text string that you want to count instances of (note that text must be enclosed in quotation marks).

NOTE: This formula must be entered as an array formula. To enter an array formula, press CTRL+SHIFT+ENTER.

Wildcard characters can be used within the COUNTIF function.

The asterisk character (*) represents more than one character. For example, to count all the cells in the range a1:a10 that contain an "x," you can use the following formula:
=COUNTIF(a1:a10,"*x*") 
 
The question mark character (?) can also be used to represent one wildcard character -- for example, to count all cells in the range whose second character is the letter, such as "ax" or "bx."
=COUNTIF(a1:a10,"?x*")

Sunday, July 1, 2012

[MSSQL] Setup SQL Server Linked Server to MySQL

Despite being completely proprietary, one of the nice connectivity features offered in SQL Server is the ability to query other servers through a Linked Server. Essentially, a linked server is a method of directly querying another RDBMS; this often happens through the use of an ODBC driver installed on the server.

Fortunately, many popular databases provide this ODBC driver, giving SQL Server the ability to connect to a wide range of other systems. I’ve already written about how to connect Oracle and SQL Server. In this post, I’m going to go through the steps necessary to connect SQL Server and MySQL.

The first step is to fetch an appropriate MySQL Connector/ODBC 5.1 download. Drivers are available for a variety of OS‘s, but we’re obviously focused on Windows or Window x64, which should correspond to the version of SQL Server installed. After you’ve downloaded and installed the driver, we have a few things to configure, so let’s get started:

Configure a MySQL DSN

The first step is to configure a MySQL data source by running the ODBC Data Source Administrator. This step is technically entirely optional, but allows a simpler configuration in the SQL Server Linked Server settings. Instead of composing a complicated MySQL connection string, we can use a simple GUI application.

Run odbcad32











If you’re using Windows Server 2003, bring up a Run dialog box with Start→Run or WinKey+R. If you’re using Windows Server 2008, use the Start Menu search box directly. In either OS, type in “odbcad32″ and hit Enter.

System DSN
















Select the System DSN tab to configure a data source for the entire system. If you only want to create the DSN for a specific user (such as your service account), use the User DSN tab. In either scenario, select the “Add…” button.

Create New Data Source















Scroll down in the Create New Data Source window and select “MySQL ODBC 3.51 Driver” and click “Finish”.

MySQL Connector Login Settings



















Once added, clicking the “Configure…” button will bring up the Connector/ODBC 3.51 Configure Data Source application. This is where you can specify all the connection settings for connecting SQL Server to MySQL. Select a Data Source Name – I typically name it after the application or database I’m connecting to. The Server, User, Password, and Database should all be obvious.


Test ODBC Connection









After you’ve entered all the required parameters, click the “Test” button to ensure a connection can be made to the MySQL server.

These settings are the bare minimum required to connect MySQL and SQL Server via a linked server, but I like to specify additional options to optimize the connection between the servers. Without these, I have run into “Out of Memory” errors that require restarting the service.

MySQL Connector Advanced Settings - Connection
















Select the Advanced tab and you’ll be placed on the “Connection″ sub-tab. Check the boxes labeled “Allow big result sets” and “Use compressed”.

Next, switch to the “Cursors/Results″ tab and select “Don’t cache results of forward only cursors”. This can actually be a performance penalty if you perform the same query multiple times to the same linked server. However, in my experience, the reason to connect SQL Server to MySQL, is to pull data into a single server, in which case, this option is perfectly suited.

Select “Force use of forward-only cursors”. When you’re done setting all these options, select the “OK” button.

MySQL Connector Advanced Settings - Cursors/Results















 

Configure Linked Server Provider

Adjusting the Linked Server Provider is simple, but it comes with a caveat: When adjusting a provider, you are adjusting it for all connections using that provider. I am not aware of any way to change these settings on a per-connection basis.

Provider Properties



















Drill down to Server Object → Linked Servers → Providers, right-click MSDASQL, and select “Properties”.

Set Provider Options

















The Provider Options for Microsoft OLE DB Provider for ODBC Drivers dialog box will open allowing you to configure several options. Ensure the following four options are checked:
  • Nested queries
  • Level zero only
  • Allow inprocess
  • Supports ‘Like’ Operator
All other options should be unchecked. When done, click “OK”.

Create Linked Server to MySQL

Finally, the last step in our process is to create the actual MySQL Linked Server.

Create a New Linked Server
















You should already have Linked Servers expanded in the Object Explorer tree. If not, find it in Server Objects → Linked Server. Once there, right-click Linked Servers and select “New Linked Server…”

New linked Server Settings

















The New Linked Server dialog box will open. Because we specified all our connection settings in the ODBC Data Source Administrator, this last step is very simple. Name the linked server. As with the Data Source Name, I like to name it after the product or database I’m connecting to. In my example, I used MYSQLAPP. Ensure that the “Other data source” option is selected and choose “Microsoft OLE DB Provider for ODBC Drivers” from the Provider dropdown. Lastly, specify the Product name and Data source. The Product name doesn’t matter so much as the Data source must match what you provided in the MySQL Connector/ODBC configuration. Press “OK” when complete.

Testing the SQL Server to MySQL connection

If everything has been set correctly, you should be able to execute a query directly again the MySQL database from SQL Server Management Studio. For example:
SELECT TOP 10 TABLE_NAME FROM MYSQL_Data...tables 
  WHERE TABLE_TYPE != 'MEMORY' 
If you’ve done everything correctly, you should get back a result set. There are several error message you might receive:
OLE DB provider "MSDASQL" for linked server "MYSQL_DATA" returned message
  "[Microsoft][ODBC Driver Manager] Data source name not found and no default
  driver specified".
Msg 7303, Level 16, State 1, Line 1
Cannot initialize the data source object of OLE DB provider "MSDASQL" for
  linked server "MYSQL_DATA".

The message indicates that the Data source name you’ve specified for the linked server does not match that of the Data Source Name specified in the MySQL Connector.
Msg 7313, Level 16, State 1, Line 1
An invalid schema or catalog was specified for the provider "MSDASQL"
  for linked server "MySQLApp".
This uninsightful error is a result of not correctly setting the options for the Linked Server Provider.
Msg 7399, Level 16, State 1, Line 1
The OLE DB provider "MSDASQL" for linked server "MySQLApp" reported an
  error. The provider did not give any information about the error.
Msg 7312, Level 16, State 1, Line 1
Invalid use of schema or catalog for OLE DB provider "MSDASQL" for linked
  server "MySQLApp". A four-part name was supplied, but the provider does
  not expose the necessary interfaces to use a catalog or schema.
This “four-part name” error is due to a limitation in the MySQL ODBC driver. You cannot switch catalogs/schemas using dotted notation. Instead, you will have to register another DSN and Linked Server for the different catalogs you want to access. Be sure and follow the three-dot notation noted in the example query.

If, however, you want to access other schemas, you can do so utilizing OPENQUERY. This is also a great way to test your connection if you’re receiving problems. The syntax looks like this:
SELECT * FROM OPENQUERY(MYSQLAPP, 
  'SELECT * FROM INFORMATION_SCHEMA.TABLES LIMIT 10')
Notice that the actual query syntax in the string must be in the MySQL format (SQL Server does not support the LIMIT keyword). Additionally, you can specify a different schema using SCHEMA.TABLENAME in the query.

Conclusion

Creating a linked server between SQL Server and MySQL is a simple process. The first time requires you to install the software and configure the Linked Server Provider, but all subsequent connections require only a DSN and Linked Server.