| Author |
Stored Procedure to change default
|
|
| JLavalley@Enlighten.Net 2005-12-14, 8:25 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
| |
| Mike Epprecht \(SQL MVP\) 2005-12-14, 8:25 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/
<JLavalley@Enlighten.Net> wrote in message
news:1134587099.580770.161300@g44g2000cwa.googlegroups.com...
> 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@Enlighten.Net 2005-12-14, 8:25 pm |
| Thanks, but that didn't do it. I get the same error:
Line 3: Incorrect syntax near '@oname'
| |
| Erland Sommarskog 2005-12-14, 8:25 pm |
| (JLavalley@Enlighten
.Net) writes:
> 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
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/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx
| |
| JLavalley@Enlighten.Net 2005-12-15, 11:23 am |
| >Why should it work?<
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
|
|
|
|