1

I have to truncate the table but getting error

Must declare the scalar variable "@Table".

Code:

DECLARE @Table VARCHAR(20) = 'ABC'

AS
BEGIN
    EXEC ('TRUNCATE TABLE abcDB.dbo.'+@Table) AT [Server]
END
3
  • 2
    What is the AS doing there? Commented Oct 27, 2016 at 6:35
  • @Martin Smith you are right now its solved by erasing the AS and write the query inside begin and end block Commented Oct 27, 2016 at 6:43
  • @Martin Smith thanks for your suggestions and time Commented Oct 27, 2016 at 6:43

3 Answers 3

2

Declare the varaible After AS keyword.

BEGIN
DECLARE @Table VARCHAR(20) = 'ABC'
EXEC ('TRUNCATE TABLE abcDB.dbo.'+@Table) AT [Server]
END
Sign up to request clarification or add additional context in comments.

6 Comments

variables aren't block scoped in TSQL.
@ahmed abdelqader I voted it up but it's saying 15+ reputation can vote and I am new member. Sorry for that
the issue would be the variable name is added in a newline
@MartinSmith, you are correct , the issue is not related to begin and End, it is related with AS keyword, so my Answer is valid, and I edited it
@ahmed abdelqader vote me to increase my reputation so that I would eligible for voting..........
|
1

Check if u have any constraints(Foreign key). If exists drop it

DECLARE @Table VARCHAR(20) = 'ABC'

BEGIN
    EXEC ('TRUNCATE TABLE abcDB.dbo.'+@Table)
END 

4 Comments

Thanks for your time
@M.K.S Welcome. And please accept any one answer if it helps you, that will help people to grow in this community.
I am new member my reputation does not allow me to accept any question....I have tried it but failed to accept the questions. vote me to increase my reputation
Thanks a lot, now I am eligibled to accept any question
0

Use sp_executesql:

DECLARE @Table VARCHAR(20) = 'ABC'
SET @sql='TRUNCATE TABLE abcDB.dbo.' + @Table
EXEC sp_executesql @sql

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.