Solved

How to add a variable to a drop statement

Posted on 2013-06-24
1
434 Views
Last Modified: 2013-06-24
Hi there

I need to get a constraint name, this is what I'm using:

DECLARE @constraint as varchar(100)
set @constraint =
(select dobj.name
from sys.columns col
left outer join sys.objects dobj
on dobj.object_id = col.default_object_id and dobj.type = 'D'
where col.object_id = object_id(N'dbo.SongShare')
and dobj.name is not null)

and then I want to run this

ALTER TABLE MSO_SongShare DROP CONSTRAINT + ' ' + @constraint
alter table MSO_SongShare drop column share
EXEC sp_rename 'MSO_SongShare.share_New', 'share', 'COLUMN'
ALTER TABLE MSO_SongShare ADD  DEFAULT ((0)) FOR share

as you can see on this line

ALTER TABLE MSO_SongShare DROP CONSTRAINT + ' ' + @constraint

it does not work, how do i get the constraint name and drop it?

thanks
0
Comment
Question by:mousemat24
1 Comment
 
LVL 16

Accepted Solution

by:
Surendra Nath earned 500 total points
ID: 39271048
you have  tse dynamic sql

declare @sql varchar(500)
set @sql = 'ALTER TABLE MSO_SongShare DROP CONSTRAINT ' + ' ' + @constraint
exec(@SQL)

Open in new window

0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now