0

My SQL knowledge is pretty limited and this seems like something that should be easy, but I can't figure it out.

I have two queries that I run with the same where clause. Previously, I've pasted the number in the where clause twice. I thought there had to be an easier way so I found that you can do variables.

My problem is when declaring the variable in the first query, it forgets it and doesn't run it for the second query. The terminology may be off on a lot of what I've explain, but the simple query below should explain it better. The second query fails and says

must declare the scalar variable @p_repid

which I have declared in the first query.

DECLARE @p_repid int=3427115
select fldRBuddyId, count(fldRBuddyId) "Repeats"
from tblMsgsOnAir_Type8 typ8
where fldCBuddyId = @p_repid
group by fldRBuddyID
having count(fldRBuddyId) > 1
order by "Repeats" desc
go

select FLDREPID,moa.FLDTGBID,tt.FLDNAME, count(*) "Count"
from TBLMSGSONAIR_1 moa
join TBLTOWERS_1 tt on moa.FLDTGBID=tt.FLDTGBID
where  fldrepid = @p_repid
group by  FLDREPID,moa.FLDTGBID,tt.FLDNAME
order by "Count" desc
go

Thanks in advance for any help.

3
  • Tag dbms used! (Since this variable thing isn't ANSI SQL.) Commented Feb 4, 2016 at 13:38
  • Re-tagged with SQL Server and T-SQL based on the code given and the error message Commented Feb 4, 2016 at 13:47
  • Thanks and sorry I didn't know the correct tags to apply. Commented Feb 4, 2016 at 14:18

2 Answers 2

3

Remove the GO between the two statements. That's MS SQL Server's batch separator.

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

2 Comments

Additional info to clarify: Variables leave scope when the batch terminates. So when you hit "go", any variables previously declared cease to exist.
Thanks. That seemed simple enough. I was given the query by someone else and wasn't sure about the "Go" between the two statements.
0

If you use "GO" command all declared variables are gone. Try removing the "GO" which is in the middle.

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.