SQL Server solution with variable name as table name

Source: Internet
Author: User
Tags end sql table name variable
server| variable | solve
Recently wrote procedure, encountered some problems. I think the question of "Use variable name as table name" is more valuable, write and share with us. Please do not hesitate to enlighten me if you have a good solution.

Scene:

If you are writing procedure, create a table dynamically based on the value of a particular variable (the table name is the value of all or part of a particular variable). For example:

DECLARE @tablename char (10)

If some statement

Set @tablename = ' Test '

You want to create a new table with the value of the variable @tablename as the table name, then you will experience problems using the CREATE TABLE @tablename (test char (8)) statement to execute in SQL Server 2k.



Resolve (Take the example):

Create if the table does not exist

IF not EXISTS (SELECT name from sysobjects

WHERE name = @tablename and type = ' U ')

Begin

set@createtable= ' CREATE table ' + @tablename + ' (myname char (2)) '

EXEC (@createtable)

End



< end >


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.