Extract the first word of a string in a SQL Server query

SELECT CASE CHARINDEX(‘ ‘, @Foo, 1) WHEN 0 THEN @Foo — empty or single word ELSE SUBSTRING(@Foo, 1, CHARINDEX(‘ ‘, @Foo, 1) – 1) — multi-word END You could perhaps use this in a UDF: CREATE FUNCTION [dbo].[FirstWord] (@value varchar(max)) RETURNS varchar(max) AS BEGIN RETURN CASE CHARINDEX(‘ ‘, @value, 1) WHEN 0 THEN @value ELSE … Read more

Return row of every n’th record

This is where ROW_NUMBER can help. It requires an order-by clause but this is okay because an order-by is present (and required to guarantee a particular order). SELECT t.id, t.key FROM ( SELECT id, key, ROW_NUMBER() OVER (ORDER BY key) AS rownum FROM datatable ) AS t WHERE t.rownum % 30 = 0 — or … Read more

When should I not use a semicolon?

T-SQL syntax does not require a semicolon to terminate a statement. Actually, this is deprecated1. I can’t remember for sure, but I think you can still get away with not using them in the upcoming SQL Server 2012, but some version after that will likely require a semi-colon for every statement. Using a semi-colon is … Read more

Using a cursor with dynamic SQL in a stored procedure

A cursor will only accept a select statement, so if the SQL really needs to be dynamic make the declare cursor part of the statement you are executing. For the below to work your server will have to be using global cursors. Declare @UserID varchar(100) declare @sqlstatement nvarchar(4000) –move declare cursor into sql to be … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)