views:

108

answers:

1

I am writing a script to update a database to add Filestream capability. The script needs to be able to be run multiple times without erroring. This is what I currently have

IF ((select count(*) from sys.columns a 
       inner join sys.objects b on a.object_id = b.object_id 
       inner join sys.default_constraints c on c.parent_object_id = a.object_id 
       where a.name = 'evidence_data' and b.name='evidence' 
          and c.name='DF__evidence_evidence_data') = 0)

begin

 ALTER TABLE evidence SET ( FILESTREAM_ON = AnalysisFSGroup )   
 ALTER TABLE evidence ALTER COLUMN id ADD ROWGUIDCOL;

end

GO

The first time I run this against the database it works fine. The second time when the if statement should be false it throws an error saying "Cannot add FILESTREAM filegroup or partition scheme since table 'evidence' has a FILESTREAM filegroup or partition scheme already." If I put a simple select into the if statement and take out the alter table filestream on line it functions correctly and does not perform the if statement. So esentially it is always running the alter table filestream on statement even if the if statement is false.

Any thoughts or suggestions would be great. Thanks.

A: 

It's hard to reason about your business logic without knowing the details, but I'd say if you only want to alter tables that don't have filestream data space defined, consider a condition based on the following query (if it returns NULL for a given table, it means that filestream data space (file group or partition scheme) is not defined:

select filestream_data_space_id from sys.tables

Pawel Marciniak
I have tried this and am still having the same issue. No matter if the sql is true or false it runs the alter statement and fails. If I put a simple select in the query it acts correctly but as soon as I put the alter statement in it fails trying to run the alter statement.
Allison
soIF (SELECT [filestream_data_space_id] FROM [analysis].[sys].[tables] where name = 'evidence') IS NULLbeginselect * from analysis.dbo.evidenceendThis does nothing but thisIF (SELECT [filestream_data_space_id] FROM [analysis].[sys].[tables] where name = 'evidence') IS NULLbeginALTER TABLE evidence SET ( FILESTREAM_ON = AnalysisFSGroup )enderrors and says the filestream is already on.
Allison