Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Create table structure using data from another table?

Status
Not open for further replies.

sfn6

Programmer
Aug 30, 2001
11
US
Hello.

I have a table (Columns) with three colums: Name, Length, Type that contains the info needed to create a new table.

I know how to create a table in Query analyzer, but how do I programatically loop through the columns table to create the columns in the new table?

I would do this manually, but there are 571 columns that need to be created.

Thanks in advance for any help!
 
Never mind! I just wrote a quick routine in Access/VBA to loop and do it. I was hoping I could learn to do it in T-SQL, but time is $$ ;).

Here's the code if anyone's interested:

Private Sub Command1_Click()
Dim cnNow As ADODB.Connection
Dim rsNow As ADODB.Recordset
Dim strSQLcreate As String
Dim strSQLget As String
Dim cName As String
Dim cLen As String

Set cnNow = CurrentProject.Connection

Set rsNow = New ADODB.Recordset

strSQLcreate = "CREATE TABLE dbo.PubSchools ("

strSQLget = "SELECT Name, Length FROM dbo.Columns"

rsNow.Open strSQLget, cnNow, adOpenDynamic, adLockReadOnly


rsNow.MoveFirst
cName = rsNow!Name
cLen = rsNow!Length
strSQLcreate = strSQLcreate & cName & " nvarchar(" & cLen & ")"
rsNow.MoveNext

Do Until rsNow.EOF
cName = rsNow!Name
cLen = rsNow!Length

strSQLcreate = strSQLcreate & "," & cName & " nvarchar(" & cLen & ")"
rsNow.MoveNext
Loop

strSQLcreate = strSQLcreate + ")"

rsNow.Close
Set rsNow = Nothing

cnNow.Execute strSQLcreate

cnNow.Close
Set cnNow = Nothing

Debug.Print strSQLcreate

End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top