declare variables in sql 2005 - sql

In my script i have few select statements and update statements, as an example
SELECT * from TABLE1
WHERE userID= 'US001'
UPDATE TABLE2
SET value= 'months'
WHERE userID='US001'
statements going so on, so in this i have to copy and paste userID to every statement.
i want to declare a variable and assign to userID to refer it, so i don't need to add userID number to every query and i need to execute
i have tried this
Delcare #theID userID
SET userID ='us001'
but didn't work it out
please let me know..
thanks

You'll need to declare the type, and assign it. In Sql Server, variables are prefixed with #, like so:
DECLARE #theID NVARCHAR(20);
SET #theID ='us001';
UPDATE TABLE2 SET value= 'months' WHERE userID=#theID;

DECLARE #theID varchar(10);
SET #theID = 'us001';
In your statement you are declaring your variable as userID, which is not a valid data type.

In addition to the previous answers, in SQL Server 2008 and higher you can also declare and set the variable in a single line.
DECLARE #UserID NVARCHAR(20) = 'us001';

This is what works for me under SQL2005 in a stored procedure:
DECLARE #name varchar(100)
SELECT #name = 'Robin'
// and this should be do the update
SET userID = #name
// or in you query it should be
WHERE userID = #name

Related

How do i convert variable name to string name?

Assume I have the following SQL snippet in SQL Server 2012:
DECLARE #fname varchar(20), #strVarName varchar(50)
SET #fname = 'cronus'
SET #strVarName = COVERT_VARIABLE_TO_STRING_NAME ( #fname)
--this should return '#fname'. this is not a value conversion this is converting a variable name to a string name
SELECT #strVarName
How do I do this?
SQL Server does not support reflection. You may be able to retrieve column or table names from its catalog views but with variables you're out of luck. Maybe you'll find another way to solve this issue with dynamic SQL.
Use dynamic sql query
DECLARE #fname varchar(20), #sql varchar(MAX)
SET #fname = 'cronus'
SET #sql = 'SELECT ' + #fname
EXEC (#sql)
There are following Character data types used to store character strings:
char,
varchar,
nvarchar,
text,
If u already used variable as String then why need to convert as a string
DECLARE #fname varchar(20), #strVarName varchar(50)
SET #fname = 'cronus'
SET #strVarName = #fname
SELECT #strVarName
if needed use CAST and CONVERT function
This is such a bizarre question, sounds like something I'd try to do.
Hmm, SQL is not supposed to do this but I guess, it doesn't mean you can't make it.
I think you would effectively have to write your own process to pull this off, something along the lines of:
Create dbo.sProcInserts stored procedure to insert values into a table:
Takes VariableName, Value and possibly table name to insert into as parameters
Create dbo.sProcExec stored procedure to execute stored procedure:
Before execute, read stored procedure into a variable
Find all variables that are SET (i.e. they have a SET #Var = OR SELECT #Var =)
After each variable set, add to your string a line that calls dbo.sProcInserts with the name of the variable and a select #Variable
Execute your newly written stored procedure
That way you don't have to actually make any modifications to your sProcs and it should catch the flow of variables and their changes through your procedure
However the requirement itself is a bit strange for me, but here is a way that could be a good start point for you:
declare #var1 int
Set #var1= 1
--some code here
declare #var2 nvarchar(max)
set #var2 = 10
--some other code here
declare #var3 bit
print ##VERSION
print 'this is fake #value inside a string'
--$ This is a Hint to help me find the Query that should parsed
declare #sql varbinary(max)
select #sql=sql_handle
from sys.sysprocesses
where spid=56
declare #q nvarchar(max)
select #q= substring(text,1,charindex('$',text)-3) from sys.dm_exec_sql_text(#sql)
Select distinct rtrim(ltrim(substring(Name,1,charindex(' ',Name)))) as Name from(
Select substring(replace(Name,'=',' '),8, Len(Name)) as Name from dbo.SplitString(#q,'declare ')
) as K
where Name like '#[^#]%'
By running the above query you will get the variables name.
Output:
#var1
#var2
#var3
You can find the source code for SplitString function Here
Note: If you are using SQL Server 2016 and your database's compatibility level is equal or greater than 130, you can also use SPLIT_STRING introduced by Microsoft it self. Learn more Here

Understanding SQL syntax

I'm a C# developer trying to become more familiar with SQL Server stored procedures.
I'm a little confused as to why the syntax in "A" works and "B" does not work with Set #id. What is happening here that makes "B" require Select instead of Set?
Example A (works)
DECLARE #currDateTime DateTime
SET #currDateTime = GetDate()
SELECT #currDateTime
Example B (does not work)
DECLARE #id int
SET #id = ID FROM [MyTable] WHERE [Field1] = 'Test'
Example C (works)
DECLARE #id int
SELECT #id = ID
FROM [MyTable]
WHERE [Field1] = 'Test'
SELECT is a built-in type of SQL clause that runs a query and returns a result-set in the format of a table or it assigns variables to the results from a query.
SET is a clause that sets a variable.
The two are very different. SELECT has various other associated clauses, such as FROM, WHERE and so on; SET does not. SELECT returns values as a result table in its normal usage; SET does not.
Admittedly, both look the same in an expression such as:
set #currDateTime = GetDate();
select #currDateTime = GetDate();
However, it is really a coincidence that the syntax for setting a single value happens to look the same.
It doesn't work because it's incorrect SQL syntax, You need SELECT when fetching data from table/view/table function.
You could use SET when using an expression though i.e:
DECLARE #Id bigint
SET #Id = (SELECT TOP 1 Id
FROM MyTable
WHERE Field1 = 'Test')

Must declare the table variable SQL server 2008

I am writing to make it easier for other techs to fix a database issue.
The goal of this query is so the techs only have to copy paste and provided 3 values but I'm running into a error
Must declare the table variable "#fromArchives".
DECLARE #maxIdentityValue INT
DECLARE #selectId varchar(60)
DECLARE #fromArchives varchar(60)
DECLARE #tableDBCC varchar(60)
SET #selectId = someColumn --This is a column in the #fromArchives
SET #fromArchives = OrderArchives --This is a table
SET #tableDBCC = Orders --This is the table to fix
SET #maxIdentityValue =
(SELECT MAX(#selectId)
FROM #fromArchives) + 1
DBCC CHECKIDENT
(#tableDBCC, RESEED, #maxIdentityValue)
GO
any ideas?
All tablename should be static in sql query.
If you want to use dynamic table or column names, you should generate the full SQL dynamically, and use sp_executesql or EXEC(sql) to execute it.
DECLARE #fromArchives varchar(60)
SET #fromArchives = OrderArchives --This is a table
EXEC('SELECT * FROM ' + #fromArchives)
Refer This Dynamic SQL Article

Dynamic update of string values in tables using Stored procedure

The following is my stored procedure to update a column in SQL SERVER
ALTER PROCEDURE [dbo].[AspPageUpdate]
(#type varchar(50),#comp varchar(50),
#place varchar(50))
AS
BEGIN
SET NOCOUNT ON;
DECLARE #tid varchar;
DECLARE #ph int;
SET #ph = CAST(#place AS int);
select #tid = Type_Id
from TypeTable
where Type_Name = #type
UPDATE TypeSetupTable
SET PLACE_HOLDERS = #ph
WHERE complexity = #comp
AND Type_Id = #tid
END
But the table is not getting updated. I think the problem is with Quotes(Strings need to be in quotes, right?).
If i'm giving static values, it is execting, like:
UPDATE TypeSetupTable SET PLACE_HOLDERS = #ph WHERE complexity = 'Simple' AND Type_Id = 'SSRS'
Please tell me a solution.
Thanks in Advance.
you didn't set the size of the variable #tid.
Are you sure of the content of that variable while executing the stored procedure?
Try to put a raiserror(#tid,15,1) and check the content of that variable.
There are blogs about the habit not to size varchar variables.
It is also officially documented that the size of unsized varchars is 1.

How to set a variable to the result of a sql query with a variable as a table name in SQL 2005

I'm currently having trouble writing a stored procedure and setting the value of a variable of type int to the results of a select statement with a variable as the tablename. I've looked at old threads and tried multiple methods, but no luck. If I'm not getting an error regarding the tablename, I end up getting an error with a variable conversion issue. I've been working on this for too long and any help would be appreciated. Below is a portion of my code. Thanks
DECLARE #BATCHNUMBER VARCHAR --value set in earlier code
DECLARE #ETABLE VARCHAR(50); --the table name
DECLARE #FIRSTDOCID INT;
SET #ETABLE = 'tablename_' + #BATCHNUMBER; --CREATE FIRST TABLE NAME
SELECT #FIRSTDOCID = MIN(D0CID) FROM #ETABLE
The error I get is: Must declare the table variable "#ETABLE"
You are trying to select from a VARCHAR, not a table. The only way to make this work is by using Dynamic SQL.
DECLARE #SQL NVARCHAR(250);
SET #SQL = 'SELECT #OUTPUT = MIN(D0CID) FROM ' + QuoteName(#ETABLE);
EXEC sp_executeSql #SQL, N'#output INT OUTPUT', #FIRSTDOCID OUTPUT;
SELECT #FIRSTDOCID;
However, I would not suggest using Dynamic SQL as this often leads to SQL injection.
You'll probably have to do something like use exec if you're dynamically building the query:
SET #QUERY = "SELECT" + ...etc.
exec(#QUERY)
Since ETABLE is a varchar, and not, as expected, a 'table variable'.