Groups | Blog | Home
all groups > sql server (alternate) > december 2005 >

sql server (alternate) : Stored Procedure to change default


JLavalley NO[at]SPAM Enlighten.Net
12/14/2005 12:02:41 PM
Can someone explain to me why the following doesn't work?

declare @oname sysname
select @oname=name from sysobjects where name like
"df__mytable__mycol%"

alter table mytable drop constraint @oname
JLavalley NO[at]SPAM Enlighten.Net
12/14/2005 1:53:54 PM
Thanks, but that didn't do it. I get the same error:

Line 3: Incorrect syntax near '@oname'
Mike Epprecht (SQL MVP)
12/14/2005 9:12:35 PM
Maybe more than one row is returned, and only one value can fit into a
variable.

This will work:

declare @oname sysname
select TOP 1 @oname=name from sysobjects where name like
"df__mytable__mycol%"

alter table mytable drop constraint @oname

Regards
--------------------------------
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland

IM: mike@epprecht.net

MVP Program: http://www.microsoft.com/mvp

Blog: http://www.msmvps.com/epprecht/

[quoted text, click to view]

Erland Sommarskog
12/14/2005 10:28:45 PM
(JLavalley@Enlighten.Net) writes:
[quoted text, click to view]

Why should it work? There are some places you can use variables in
T-SQL for object names, but in most places you can't. Check out the
syntax chart in Books Online when in doubt.

You can use dynamic SQL: EXEC('ALTER TABLE tbl DROP CONSTRAINT ' + @oname)

For more information about dynamic SQL, see this article on my web site:
http://www.sommarskog.se/dynamic_sql.html.

--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
JLavalley NO[at]SPAM Enlighten.Net
12/15/2005 8:14:22 AM
[quoted text, click to view]
What kind of question is that? Not relevant here. I asked why it
doesn't...

thank you for your response, not only did you solve my problem (using
"exec") but you educated me on the fact that I can't use variables for
object names in most places.

PS.
It should work because it's much more intuitive than having to create
and execute a string of the same command.
It should work because that would be consistant with other T-SQL
commands
AddThis Social Bookmark Button