Archive for category SQL Server
Clear down transaction logs
Posted by shawson in SQL Server on August 31st, 2010
A bit of syntax that I can never remember off the top of my head! SQL 2005 ‘Transaction Log is Full on database xxx’
DBCC SHRINKFILE('dbname_log', 1)
BACKUP LOG dbname WITH TRUNCATE_ONLY DBCC SHRINKFILE('dbname_log', 1)
Cross server queries in SQL Server
Posted by shawson in SQL Server on August 26th, 2010
Without linking the servers you can do one off queries against another server using the OPENDATASOURCE or OPENROWSET functions. You will need to first enable “Ad Hoc Distributed Queries” as this is disabled by default- this can be achieved using sp_configure (if you’re logged in as sa)
sp_configure 'Ad Hoc Distributed Queries', 1 reconfigure
Once active you can use the function like this;
SELECT
*
FROM
OPENDATASOURCE('SQLOLEDB', 'Data Source=<servername>;User ID=<user>;Password=<password>').<dbname>.<dbo>.<tablename>
There is also an OPENROWSET function;
SELECT
source.*
FROM
OPENROWSET('SQLOLEDB', 'Data Source=<servername>;User ID=<user>;Password=<password>', 'SELECT * FROM <dbname>.<dbo>.<tablename>') as source
Thanks to Richard who dug this little nugget up from the interwebs.
Grant Execute Permissions for all sprocs on SQL 2005
Posted by shawson in SQL Server on August 24th, 2010
So I did a post for SQL 2000 aaages ago showing how to do this- it’s a lot easier in SQL 2005 but i always forget the syntax as i rarly have to use it.
Open a new query editor on your selected database server then run this;
use <database_name>; /* CREATE A NEW ROLE */ CREATE ROLE db_executor /* GRANT EXECUTE TO THE ROLE */ GRANT EXECUTE TO db_executor
Then right click your database user (under security for the given database) and tick the new db_executor role. You’re done!
Example update with left outer join in SQL Server
Posted by shawson in SQL Server on June 16th, 2010
I always seem to remember the access syntax for this rather than the sql server version–
update
hachette_digitalideas_import
set
harrietId = u.Id
from
hachette_digitalideas_import h
left outer join user_group u
ON (h.email = u.email or h.[full name] = u.name) AND u.btype = 'u'
As opposed to the following in access;
update
hachette_digitalideas_import
left outer join user_group u
ON (h.email = u.email or h.[full name] = u.name) AND u.btype = 'u'
set
harrietId = u.Id
Cross Apply in SQL
Posted by shawson in SQL Server on June 8th, 2010
In Summary: I basically wanted to take the data in a table, then linked data from another table concatenated into a comma separated string, and attached as a varchar column on the end of the first table!
I have the mis-fortune of working on a terrible intranet system based on technology built by a company I won’t actually name- so for the purpose of this post, lets say they are called Source. It’s basically a big buggy CMS powered by some aging and creaky classic asp files and lashing of very frail javascript (this isn’t a legacy system- it was installed in the company around a year ago!). It allows you to build forms and data grids, but is quite restrictive with how you attach these to the database- you cannot for example use a stored procedure as a data source- it has to be a table or a view.
We have an internal app to allow staff to order with a table structure like so;
OrderHeader -> OrderDetail -> Publisher -> Warehouse
On the order header view page we need to know which warehouses are involved, which means a query going right down the chain from product on the order line, to the publisher, down to which warehouse that publisher is based at- because we can only tie to a single table or view I had a problem unless i wanted loads of repeated rows- after some googling I found CROSS to be what I was after;
Based on the above post I was able to build SQL like so;
SELECT
OrderHeader.id,
OrderHeader.user_id,
OrderHeader.OrderDate,
Users.name,
WareHouses = LEFT(o.list, LEN(o.list)-1)
FROM
OrderHeader INNER JOIN
User ON OrderHeader.UserId = User.UserId LEFT OUTER JOIN
CROSS APPLY
(
SELECT distinct
CONVERT(VARCHAR(50), WareHouse.Name) + ',' AS [text()]
FROM
WareHouse
INNER JOIN Publishers ON WareHouse.id = Publishers.WarehouseId
INNER JOIN OrderDetailLine ON Publishers.PublisherID = OrderDetailLine.PublisherID
WHERE
OrderDetailLine.OrderHeaderId = OrderHeader.OrderHeaderId
ORDER BY
CONVERT(VARCHAR(50), WareHouse.Name) + ','
FOR XML PATH('')
) o (list)
This bought me back each row, with a comma separated list of the warehouse names in the end column which i could then filter on!
Full Text Reindex, scheduled job has no steps!
Posted by shawson in SQL Server on January 12th, 2010
We have a SQL Server 2005 box, on which we have a database which has a full text index. The database gets a massive refresh of its data each night, meaning the full text index needs rebuilding. I added a schedule to my full text index (Databases > [DBName] > Storage > Full Text Catalogs > Right click your index – click properties > Population Schedule) and this created me a new job (SQL Server Agent > Jobs) but when i opened it up and went to steps, nothing was there! If i tried running the job it would fail because there are no steps!
I found this as a documented bug in the initial release candidate of sql 2005 (since fixed in the service packs) on the microsoft connect site, and added a workaround – basically just add your own job, using the following sql (which i found on msdn) to rebuild your index;
ALTER FULLTEXT CATALOG [catalogue_name] REBUILD;
Of course, this is only a workaround until we can get the latest service pack installed.
How to run SQL Profiler against local SQL Express instances
Posted by shawson in .net, SQL Server on December 9th, 2009
I’m building a project using entity framework and wanted to ensure it wasn’t going mental and spamming the database with more queries than it should- this requires SQL Profiler, but i didn’t know how to connect it to my local instance of sql (I had just added an MDB file to the app’s app_data folder, so it was running via local sql express)
Turns out it’s easy- you just connect to .\SQLEXPRESS database and then execute this query against the master database;
SELECT owning_principal_name, instance_pipe_name FROM sys.dm_os_child_instances
From the results you will be able fish out the “named pipe” that you can just put into the server name box when connecting with profiler.

Sql Profiler connection dialogue
via Brad Wilson: Profiling SQL Server Express User Instances.
Whats the definitive maximum size of an email address?
Posted by shawson in E-Commerce, Email, SQL Server on December 1st, 2009
I’ve written lots of app’s which store email addresses, and usually go for a nvarchar(100) to store them, but thought I would find out once and for all, what the actual maximum size was- just out of curiousity.
Having googled around, I came across a couple of lengthy posts on the matter (here and here), quoting figures from various standard (which seemed to point at 320 character), then corrections to those standards by members of ICANN based on the SMTP spec and so on and so forth…
After much trawling, it seems the official answer is : 254 characters (256 including the standard <> brackets around the address)
Conditional Order-By clause in SQL 2005
Posted by shawson in SQL Server on July 23rd, 2009
In SQL Server 2005 onwards you can have conditional Order By clauses in your stored proc’s- for example
SELECT EmployeeID, SalariedFlag
FROM HumanResources.Employee
ORDER BY CASE SalariedFlag WHEN 1 THEN EmployeeID END DESC
,CASE WHEN SalariedFlag = 0 THEN EmployeeID END;
GO
ASP.Net Role & Membership Providers (Under IIS7) – DOESN’T Work!
Posted by shawson in .net, SQL Server on July 16th, 2009
Ok well, it does, but I’ve had a very stressful afternoon at it’s merciless hands! Just trying to get the ASP.Net roles & membership working on asp.net 3.5, using IIS7. I created the project and clicked “ASP.Net Confguration” from the project menu, but no working providers existed.
I defined some custom providers and nothing would get picked up.
It turns out, under IIS you need to define a connection string with a specific name to make this work–
<connectionStrings>
<clear/>
<add name="LocalSqlServer" connectionString="your real connection string goes here!" />
</connectionStrings>
So we’re clearing out the default inherited connection strings then overriding the default LocalSqlServer connection to have the correct connection to our real database, as this appears to be the connection string it defaults to.
Save the web.config file, the fire up the “ASP.net configuration” site again and you should be away!
Thanks to Mr Ledger for channelling the awesome power of google through himself to yield that nugget of joy and relief!