-1

I would like to create a database with a couple tables in it. I am using SSMS and it is easy enough to accomplish said task by right-click creating, but I would like to use query/command line (not sure how to phrase that).

Create a database and table

    CREATE DATABASE test_employees;

    CREATE TABLE dbo.EmployeesBasicInfo
    (
        MyKeyField VarChar(8) PRIMARY KEY,
        FirstName VarChar(30) NOT NULL,
        LastName VarChar(50) NOT NULL,
        DateStarted DateTime NOT NULL,
        Age Int NOT NULL,
        ModifiedDate DateTime NULL
    );

But I have no idea where the table goes or how to move/link it to database test_employees.

Also, if you feel ambition in answering my question then the next step is to auto-generate data for all fields. Any links you could provide would be helpful. And, if anything I'm doing is not best-practice please let me know - I'm just getting into SQL.

4

2 回答 2

3

After you've created the database you need to

Use test_employees
Go

This sets your current working database for subsequent statements.

Alternatively you can qualify your create table with the database name

Create Table test_employees.dbo.EmployeesBasicInfo (
    MyKeyField varchar(8) primary key,
    FirstName varchar(30) not null,
    LastName varchar(50) not null,
    DateStarted DateTime not null,
    Age int not null,
    ModifiedDate datetime null
);

You've probably created this table in your default database, which may well be master.

Also for any recent version of SQL Server, consider using datetime2 instead of datetime (or date if you don't need the time component). It's better in all respects.

于 2013-10-06T19:40:26.380 回答
1

Here is some code to create a table 1st and then you can add some test data into it to practice with .......

TO CREATE A TABLE :

Create Table dbo.BasicInfo (
    MyKeyField INT primary key IDENTITY(1,1),
    FirstName varchar(30) not null,
    LastName varchar(50) not null,
    DateStarted DateTime not null,
    Age int not null,
    ModifiedDate datetime null
)
GO

TO ADD PRACTICE DATA:

DECLARE @Value INT = 1

WHILE @Value <= 100
    BEGIN 
        INSERT INTO dbo.BasicInfo (FirstName, LastName, DateStarted, Age, ModifiedDate)
        VALUES           ('First_Name_' + CAST(@Value AS VARCHAR), 'Last_Name_'+ CAST(@Value AS VARCHAR), DATEADD(DAY, -CONVERT(INT, (5000+1)*RAND()), GETDATE()),
                     18 + CONVERT(INT, (30-10+1)*RAND()),  DATEADD(DAY,  10 + (30-10)*RAND() ,DATEADD(DAY, -CONVERT(INT, (5000+1)*RAND()), GETDATE()))) 
        SET @Value = @Value + 1
    END

if you want to add more then 100 rows in your table just replace the number or rows you wish to add to your table with 100 in this code

于 2013-10-06T21:22:03.533 回答