2

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'
2
  • 1
    FROM is belong to SELECT not to SET. For more information look at this link Commented May 31, 2016 at 11:06
  • When You retrieve value from table use 'Select' . In case of simple assignment statement You can use 'Set' Commented May 31, 2016 at 11:12

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.