-
Using a Case Statement in a SQL Where Clause
-
Alphabetizing Words in a Phrase Using SQL
I had the need to today to alphabetize a phrase using SQL. For example, I needed “red cowboy pretty hat” to read “cowboy hat pretty red”. Here is the code I wrote to do so: declare @input varchar(100) set @input = “red cowboy pretty hat” –declarations DECLARE @i int ,@len int ,@word varchar(100) ,@char varchar(1) ,@newphrase varchar(1000) –Variable/Constant initializations SET @i = 1 SET @len = LEN(@input) SET @word = “” SET @newphrase = “” create table #temp(word varchar(100)) WHILE @i < @len begin SET @char = SUBSTRING(@input, @i, 1) IF @char = ” ” begin –add word to temp table…
-
Find and Delete Duplicates in SQL
We all know we shouldn’t have duplicates in the database. And despite my best efforts, somehow they sneak in from some legacy code, or from the hyper-active-compulsory-submit-the-form-fifty-times-in-five-seconds-bloke. So now and then I find myself writing the same SQL to track them down. Most solutions online say that you have to use a temporary table or…
-
Using Case in Order By with Group By
-
Using SQL Dateparts
-
Using SQL Where Clauses for Searching
One piece of SQL lore I take for granted is COALESCE(). The dictionary definition describes SQL's use pretty close as “To bring or come together into a united whole”. Books Online states in laymans terms that SQL allows you to pass any number of arguments to the function, and it will return the first non-null…
-
Retrieving Values from SQL Exec()
Never had a good reason to do this up until now, but if you need to get a value from a generated sql string, there are a few hoops you must jump through. Example: declare @table varchar(20) ,@username varchar(30)–can't use double quotes w/out this :)SET QUOTED_IDENTIFIER OFF–set your variablesselect @table = 'tblcustomers' ,@username = 'webmaster'–create…
-
Sql Dependencies
-
Count Distinct Rows in SQL Server
Question: How do you count distinct rows in a query? 1st Try: I *thought* this would work: select distinct count(taskid) from #temp however, it returned the count of all taskid's. 2nd Try: then I tried keeping duplicates out to begin with, so I could just do a normal count(taskid). That wasn't fool proof. Solution: Just…
-
Generate Inserts from a Stored Procedure