How to use a DECLARE statement

I'm relatively new to SQL and I'm still trying to learn how to set up a DECLARE statement.
For starters I don't really understand what the DECLARE is doing.. I understand select, and from what I believe DECLARE does is changes the field from one data output to a different data output.
I'm also brand new to this forum and from how I see it you guys write your example's different from how mine looks but I'm not sure exactly what everything means here.
So far this is how far I've gotten.
DECLARE my_table where my_column_name = ''

Are you talking about Microsoft SQL Server syntax?

Yes, currently using Microsoft SQL Server Management Studio.

declare as the name implies allows you to assign and retrieve SQL values. as in maths you declare x, y, z
there are times that the variable could be a table variable

DECLARE @ProductTotals  TABLE(ProductID int,revenue money)

After which you can populate (or add data) into this table variable
Then you can filter user where clause to filter data in that table variable using

select * from @ProductTotals where ProductID = 13
1 Like

@BDecked,
You are confusing columns with variables. DECLARE @i int; declares a variable of the int data type.
A column also has a data type:

DROP TABLE IF EXISTS dbo.Example;
GO

CREATE TABLE dbo.Example
   ( Id int IDENTITY(1, 1) NOT NULL PRIMARY KEY
   , ExampleString varchar(200)
   );
GO

DECLARE @exampleString varchar(200) = 'Example text';

INSERT INTO dbo.Example (ExampleString)
VALUES (@exampleString);
SELECT 
   Id
 , ExampleString 
FROM dbo.Example;

DROP TABLE dbo.Example;
GO

image

1 Like

Thanks! That should help when referencing tables and specifics when I'm asking questions in the future.