Link to home
Start Free TrialLog in
Avatar of emi_sastra
emi_sastra

asked on

Delete table with year and month

Hi All,

I try to delete table data. Please see below :

WHILE ( @IntMonth <= 12)
BEGIN
    DELETE FROM 'TDJURNAL' + ' + @Year + ' + @IntMonth

      SET @IntMonth = @IntMonth + 1
END

For example table name TDJURNAL201701 to 201712.

How could I do it ?

Thank you.
Avatar of PortletPaul
PortletPaul
Flag of Australia image

NO!

you won't get "leading zeros" to start with e.g. 1 <> "01"

and you cannot inject a table name into SQL through a variable like that, you need "dynamic sql" to do that.

Do you want to "truncate" each table?
https://docs.microsoft.com/en-us/sql/t-sql/statements/truncate-table-transact-sql
Avatar of emi_sastra
emi_sastra

ASKER

Hi PortletPaul,

    DELETE FROM 'TDJURNAL' + ' + @Year + ' + @IntMonth

Would you please how to code correctly for the above statement ?

Thank you.
Please answer my question:  

Do you want to "truncate" each table? read the documentation first, url provided above
I want to use variable for table name.

That's why I want to use looping.

Thank you.
sigh....

Please answer my question:  

Do you want to "truncate" each table? read the documentation first, url provided above

only then can I provide more... I need to know if you want to truncate those tables, that is why I asked the question.
Just want to delete data as I code.

Thank you,
From table TDJURNAL201701, XXXX201702 and etc.
Using looping or any other better way.

Thank you.
ASKER CERTIFIED SOLUTION
Avatar of PortletPaul
PortletPaul
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
- I really don't know how to help - fully - if I don't understand the nature of those deletion.
Yes, it is the right way.

Great. It works.

Thank you very much fo your help.
Great.