My code is as follows:
SET @var = (SELECT var FROM dbo.varDB WHERE varName = @varName)
IF (@@ROWCOUNT > 0)
BEGIN
//carry out insert
END
Am I right in saying this will always return a 1 for @@ROWCOUNT as it carries out an assignment last?
If so, what would be the most elegant solution to allow me to:
- Create variable with the result from my query stored in it
- Test if the query returns any results
The reason it returns one is because you’ve assigned exactly one value (some arbitrary value). You should be using
EXISTSinstead of doing a manual count anyway, as @Sive suggests. The reason is that EXISTS can perform no worse than COUNT, and in the use case you’re describing, it doesn’t really matter what the actual count is anyway. You want to know if the count is zero or greater than zero.The problem with assigning that value to a variable in the way you’ve done it, is what happens if there are multiple rows that match? Let’s try it:
Result:
Now, if
varnameis unique, I would do this:If
varnameis not unique, then I’m not sure what you’re going to do with a single value. Which one did it pull? Imagine this scenario:Will
@varbe 1 or 3? Who knows? Why does it matter which one it is if you’re only capturing one of potentially many values? Are you going to do something with that row but not the others?In addition, if your intention is to insert data from this table, why not simply throw out the up-front check, the row count etc. and just say:
The insert won’t happen if the row doesn’t exist.