Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column creation and use

I am fairly new to SQL, so not sure if this is just a SQL compiler thing or not. When I have used SQL before it's been through JAVA or PHP, never just straight SQL. I am using SQL Server 2005 and attempting to add a column to my table, and then populate it. Here is what I have now:

ALTER TABLE House DROP COLUMN CustomerType
ALTER TABLE House ADD CustomerType char(11)

UPDATE House
SET CustomerType = CASE
    WHEN ... THEN...
    WHEN ... THEN...
    ELSE "Other"
    END

However, when I try and compile this it errors since CustomerType in the UPDATE function hasn't been defined yet. Is there any way to run this so that it will compile and add the column and update it, or do I have to run it in multiple executes?

Thanks!

like image 243
user416516 Avatar asked Dec 07 '22 02:12

user416516


1 Answers

Use multiple files for each operation, or put "GO" between the steps:

ALTER TABLE House DROP COLUMN CustomerType
GO

ALTER TABLE House ADD CustomerType char(11)
GO

UPDATE House
SET CustomerType = CASE
    WHEN ... THEN...
    WHEN ... THEN...
    ELSE "Other"
    END
GO

This works in SQL Server Management Studio - it's not a T-SQL features, but a feature of Mgmt Studio to separate the T-SQL "batches" of SQL commands.

Update: if you want to make your script so that it can be run multiple times, the more useful approach would be to check for the column's existance, and only add it if it doesn't exist yet - no point in always dropping and re-adding it, if it's already there!

To do that, use something like:

IF NOT EXISTS(SELECT * FROM sys.columns WHERE name = 'CustomerType' 
                       AND object_id = OBJECT_ID('House'))
   ALTER TABLE dbo.House ADD CustomerType CHAR(11)
GO

This snippet of code checks the SQL catalog view sys.columns to see if that column already exists in that table - if not, it's created. When you run this code against your table a thousand times, the first time around, the column gets created, and any subsequent run will do nothing - since that column already exists. Much cleaner than constantly dropping and re-adding a column!

like image 171
marc_s Avatar answered Dec 28 '22 20:12

marc_s