Dynamically create columns sql

You will want to use a PIVOT function for this. If you have a known number of columns, then you can hard-code the values: select name, [Bronze], [Silver], [Gold], [Platinum], [AnotherOne] from ( select c.name, cr.description, r.typeid from customers c left join rewards r on c.id = r.customerid left join customerrewards cr on r.typeid = … Read more

How to fix “Must declare the scalar variable” error when referencing table variable?

This is a long standing parser issue. You need to get rid of the table prefix or wrap it in square brackets. i.e. delete from @CompanyGroupSites_Master where CompanyGroupID = @CompanyGroupID or delete from @CompanyGroupSites_Master where [@CompanyGroupSites_Master].CompanyGroupID = @CompanyGroupID Not delete from @CompanyGroupSites_Master where @CompanyGroupSites_Master.CompanyGroupID = @CompanyGroupID

Remove only leading or trailing carriage returns

Find the first character that is not CHAR(13) or CHAR(10) and subtract its position from the string’s length. LTRIM() SELECT RIGHT(@MyString,LEN(@MyString)-PATINDEX(‘%[^’+CHAR(13)+CHAR(10)+’]%’,@MyString)+1) RTRIM() SELECT LEFT(@MyString,LEN(@MyString)-PATINDEX(‘%[^’+CHAR(13)+CHAR(10)+’]%’,REVERSE(@MyString))+1)

How to let SQL Server know not to use Cache in Queries?

DBCC FREEPROCCACHE Will remove all cached procedures execution plans. This would cause all subsequent procedure calls to be recompiled. Adding WITH RECOMPILE to a procedure definition would cause the procedure to be recompiled every time it was called. I do not believe that (in SQL 2005 or earlier) there is any way to clear the … Read more

How to query xml column in tsql

How about this? SELECT EventID, EventTime, AnnouncementValue = t1.EventXML.value(‘(/Event/Announcement/Value)[1]’, ‘decimal(10,2)’), AnnouncementDate = t1.EventXML.value(‘(/Event/Announcement/Date)[1]’, ‘date’) FROM dbo.T1 WHERE t1.EventXML.exist(‘/Event/Indicator/Name[text() = “GDP”]’) = 1 It will find all rows where the /Event/Indicator/Name equals GDP and then it will display the <Announcement>/<Value> and <Announcement>/<Date> for those rows. See SQLFiddle demo

TSQL left join and only last row from right

SELECT post.id, post.title, comment.id, comment.message FROM post OUTER APPLY ( SELECT TOP 1 * FROM comment с WHERE c.post_id = post.id ORDER BY date DESC ) comment or SELECT * FROM ( SELECT post.id, post.title, comment.id, comment.message, ROW_NUMBER() OVER (PARTITION BY post.id ORDER BY comment.date DESC) AS rn FROM post LEFT JOIN comment ON comment.post_id … Read more