SQL Views – no variables?

You are correct. Local variables are not allowed in a VIEW. You can set a local variable in a table valued function, which returns a result set (like a view does.) http://msdn.microsoft.com/en-us/library/ms191165.aspx e.g. CREATE FUNCTION dbo.udf_foo() RETURNS @ret TABLE (col INT) AS BEGIN DECLARE @myvar INT; SELECT @myvar = 1; INSERT INTO @ret SELECT @myvar; … Read more

T-SQL loop over query results

You could use a CURSOR in this case: DECLARE @id INT DECLARE @name NVARCHAR(100) DECLARE @getid CURSOR SET @getid = CURSOR FOR SELECT table.id, table.name FROM table OPEN @getid FETCH NEXT FROM @getid INTO @id, @name WHILE @@FETCH_STATUS = 0 BEGIN EXEC stored_proc @varName=@id, @otherVarName=”test”, @varForName=@name FETCH NEXT FROM @getid INTO @id, @name END CLOSE … Read more

Select query to remove non-numeric characters

See this blog post on extracting numbers from strings in SQL Server. Below is a sample using a string in your example: DECLARE @textval NVARCHAR(30) SET @textval=”AB ABCDE # 123″ SELECT LEFT(SUBSTRING(@textval, PATINDEX(‘%[0-9.-]%’, @textval), 8000), PATINDEX(‘%[^0-9.-]%’, SUBSTRING(@textval, PATINDEX(‘%[0-9.-]%’, @textval), 8000) + ‘X’) -1)

Search for one value in any column of any table inside a database

How to search all columns of all tables in a database for a keyword? http://vyaskn.tripod.com/search_all_columns_in_all_tables.htm EDIT: Here’s the actual T-SQL, in case of link rot: CREATE PROC SearchAllTables ( @SearchStr nvarchar(100) ) AS BEGIN — Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved. — Purpose: To search all columns of all tables for a … Read more

String.Format like functionality in T-SQL?

If you are using SQL Server 2012 and above, you can use FORMATMESSAGE. eg. DECLARE @s NVARCHAR(50) = ‘World’; DECLARE @d INT = 123; SELECT FORMATMESSAGE(‘Hello %s, %d’, @s, @d) — RETURNS ‘Hello World, 123’ More examples from MSDN: FORMATMESSAGE SELECT FORMATMESSAGE(‘Signed int %i, %d %i, %d, %+i, %+d, %+i, %+d’, 5, -5, 50, -50, … Read more

How to insert default values in SQL table?

Best practice it to list your columns so you’re independent of table changes (new column or column order etc) insert into table1 (field1, field3) values (5,10) However, if you don’t want to do this, use the DEFAULT keyword insert into table1 values (5, DEFAULT, 10, DEFAULT)

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