- #1
SlurrerOfSpeech
- 141
- 11
I use SQL Server at my job and for my personal projects (only because I'm familiar with it). Nevertheless I am always amazed at how the language doesn't provide any simple ways of solving common problems.
For example, let's say I have some data which represents rows I want to insert or update in another table. I first have to create a temp table with the same column definition as the target table. This is a lot of busy-work when the target table has dozens of columns. Then I have to insert all this data into the temp table. Then I have to use a MERGE statement which involves a lot of syntax and, by the way, can't UPDATE more than 1 column! You are out of luck if you want to update both "EmailAddress" and "FirstName" for any MATCHED "UserId". I've seen users on MSDN and TechNet as far back as 2007 request to Microsoft that they change this. It remains the same.
Another example. I want to iterate through a list of values in a column, basically the equivalent of
Here's how you to that in T-SQL:
and that's probably wrong and there's no way to step-through debug it.
For example, let's say I have some data which represents rows I want to insert or update in another table. I first have to create a temp table with the same column definition as the target table. This is a lot of busy-work when the target table has dozens of columns. Then I have to insert all this data into the temp table. Then I have to use a MERGE statement which involves a lot of syntax and, by the way, can't UPDATE more than 1 column! You are out of luck if you want to update both "EmailAddress" and "FirstName" for any MATCHED "UserId". I've seen users on MSDN and TechNet as far back as 2007 request to Microsoft that they change this. It remains the same.
Another example. I want to iterate through a list of values in a column, basically the equivalent of
Code:
for(int id in MyTable.Select(t => t.Id))
{
// ...
}
Here's how you to that in T-SQL:
Code:
CREATE TABLE #ids (rn INT, id INT)
INSERT INTO #ids (rn, id)
SELECT DISTINCT ROW_NUMBER() OVER(ORDER BY Id), Id
FROM MyTable
DECLARE @i INT = 0
DECLARE @n INT = (SELECT COUNT(*) FROM #ids)
WHILE(@i < @n)
BEGIN
DECLARE @id INT = (SELECT TOP 1 id FROM #ids WHERE rn = @k)
// ...
@i = @i + 1
END
and that's probably wrong and there's no way to step-through debug it.