93

I was browsing through the questions and noticed this:

SELECT prodid, issue
FROM Sales 
WHERE custid = @custid 
AND datesold = SELECT MAX(datesold) 
             FROM Sales s 
             WHERE s.prodid = Sales.prodid
                  AND s.issue = Sales.issue
                  AND s.custid = @custid

I was wondering what the "@" does in front of custID? Is it just a way of referencing the custID from the table being selected?

Colin Brock
  • 21,267
  • 9
  • 46
  • 61
Levi
  • 12,214
  • 14
  • 43
  • 47

7 Answers7

79

The @CustID means it's a parameter that you will supply a value for later in your code. This is the best way of protecting against SQL injection. Create your query using parameters, rather than concatenating strings and variables. The database engine puts the parameter value into where the placeholder is, and there is zero chance for SQL injection.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Kibbee
  • 65,369
  • 27
  • 142
  • 182
  • ZERO? Really? 'SELECT * FROM TABLEn WHERE ID = ' & @Kibbee –  Dec 16 '08 at 16:07
  • 10
    @Mark: Could you explain how that's a valid SQL injection attempt? As far as I can see, it would error out if sent to SqlServer. – Michael Todd Jul 27 '09 at 18:47
  • 6
    The reason that there is no possibility of SQL injection is that the `@CustID ` is replaced with a string. When that database receives one of these variables it knows not to escape the variable for anything inside of it. – Patrick548 Nov 29 '12 at 19:01
  • Using concatenation of strings for an sql query, you say could lead to sql injection problems. However, if it's used in the api(public/private) that's consumed by your own dev team,, then that should not be a problem right?? – Eswar Oct 01 '18 at 10:43
  • @Kibbee, so do I have to use @? if we get rid of @, then custid is still a variable name? –  Feb 28 '19 at 02:59
36

@ is used as a prefix denoting stored procedure and function parameter names, and also variable names

Steven A. Lowe
  • 60,273
  • 18
  • 132
  • 202
4

You may be used to MySQL's syntax: Microsoft SQL @ is the same as the MySQL's ?

ine
  • 14,014
  • 8
  • 55
  • 80
3

It's a parameter that you need to define. To prevent SQL injection, you should pass all your variables as parameters.

nullromo
  • 2,165
  • 2
  • 18
  • 39
bendewey
  • 39,709
  • 13
  • 100
  • 125
2

What you are talking about is the way a parameterized query is written. '@' just signifies that it is a parameter. You can add the value for that parameter during execution process

eg:
sqlcommand cmd = new sqlcommand(query,connection);
cmd.parameters.add("@custid","1");
sqldatareader dr = cmd.executequery();
Samiksha
  • 6,122
  • 6
  • 29
  • 28
0
publish data where stoloc = 'AB143' 
|
[select prtnum where stoloc = @stoloc]

This is how the @ works.

Tisho
  • 8,320
  • 6
  • 44
  • 52
marc
  • 1
0

@ followed by a number is the parameters in the order they're listed in a function.

ZeroPhase
  • 649
  • 4
  • 21