Is there a way to declare a list of items in an sql server stored procedure using T-SQL and then loop through the items?
I’m trying to do something like this:
input_string = 'my dog has fleas.'
list_remove = 'a', 'e', 'i', 'o', 'u'
for each item in list remove
input_string = replace(input_string, item, '')
end
And in the end input_string would be ‘my dg hs fls.’
I know we can create a table in a stored procedure. Is that the best way to do something like this?
You have a few options. OMG Ponies is one. You can also use a table variable (@) or a temp table (#). The main difference between @ and # is that the @ table is a variable and stores the information in memory and the # table stores it in the temp database (in a way that allows for duplicates if 2 or more copies of the sp are running at the same time). You will find that if your table is larger than a few dozen records the @ table might become slow. This is because of how it is stored. Read this from Stackoverflow for more info. Also, you can use a while loop but if you plan on having a ton of columns in the temp table I would use a cursor, read the msdn article for more information. Cursors also allow you to move back and forth easily in your table. Also, if you want them to be fast just use the FAST FORWARD option which makes them roughly as fast as a WHILE loop in SQL.