473,406 Members | 2,894 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

t-sql alter table udf help!

Hi,

I'm trying to write a function check if a column exists on a table, and
creates it if it doesn't. The line that the query analyzer is citing
is noted. It seems unhappy taking variables in the ALTER TABLE
command. I can think of a hack around this, but I'm hoping there's a
better way? Muchas gracias in advance :)

-DJ
Code follows

CREATE FUNCTION fieldCreator
(@TableName varchar(20),
@FieldName varchar(20))
RETURNS BIT
AS
BEGIN
if (EXISTS (SELECT count (objname)
FROM ::fn_listextendedproperty (NULL, 'user', 'dbo', 'table',
@TableName, 'column', @FieldName)
GROUP BY objname))
BEGIN

ALTER TABLE @TableName ADD @FieldName int DEFAULT 4 --ERRORS HERE!!!
EXEC sp_addextendedproperty 'caption', 'Created by script for
analysis', 'user', dbo, 'table', @TableName, 'column', @FieldName
return 1
END
return 0
END
GO

Jul 23 '05 #1
8 9716
Try using the sp_executesql stored procedure

eg

declare @sql as nvarchar(500)
select @sql = 'alter table ' + @TableName + ' ADD ' + @FieldName + '
int DEFAULT 4'
exec sp_executesql @sql

Jul 23 '05 #2
David Housman (dh******@gmail.com) writes:
I'm trying to write a function check if a column exists on a table, and
creates it if it doesn't. The line that the query analyzer is citing
is noted. It seems unhappy taking variables in the ALTER TABLE
command. I can think of a hack around this, but I'm hoping there's a
better way? Muchas gracias in advance :)


To start with, you cannot invoke ALTER TABLE from a function. A UDF
must not change database state. But you use a stored procedure instead.

And, yes, you cannot use variables in the ALTER TABLE statement. You need
to use dynamic SQL for this sort of thing. The sample from PromisedOyster
should be enough to get you going. For a much longer discussion on
dynamic SQL - on when to use it and when to not - there is an article
on my web site, http://www.sommarskog.se/dynamic_sql.html, that you
may find interesting.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #3
You have a few more problems here

You can't use alter table within a function.
You can't call a stored proc from a function
You can't exec dynamic sql from a function

Nigel Rivett
www.mindsdoor.net
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #4
Hi,

Thanks for the help- I changed the function to a procedure, and used
sp_executesql to execute the dynamic sql. In return for your help, I
promise to go easy on you when the revolution comes :-D. Fixed script
is below, if anyone cares to disprove the theory that the crap I
produce is useless to anyone other than me :).

-DJ

IF EXISTS (SELECT *
FROM sysobjects
WHERE name = N'sp_fieldcreator'
AND type = 'P')
DROP Procedure sp_fieldcreator
GO

CREATE Procedure sp_fieldcreator
(@TableName varchar(20) = 'SelectedGroupsAtCMU',
@FieldName varchar(20))

AS
BEGIN
DECLARE @sql1 nvarchar(400)
DECLARE @sql2 nvarchar(400)
if (not EXISTS (SELECT count (objname)
FROM ::fn_listextendedproperty (NULL, 'user', 'dbo', 'table',
@TableName, 'column', @FieldName)
GROUP BY objname))
BEGIN
select @sql1 = 'alter table ' + @TableName + ' ADD ' + @FieldName +
'
int DEFAULT 4'
exec sp_executesql @sql1
EXEC sp_addextendedproperty 'description', 'Created by script for
analysis', 'user', dbo, 'table', @TableName, 'column', @FieldName

END
select @sql2 = 'UPDATE ' + @TableName + ' SET ' + @FieldName +'= 4
WHERE '
+ @FieldName + ' is null OR ' + @FieldName +' != 1'
exec sp_executesql @sql2
END
GO

Jul 23 '05 #5
Well I would question the use of such a procedure.
And even if it was useful the idea of checking the existence of a column
by the extended property is a bit dubious.
And even if that was ok count(objname) in an existence check?
And then a group by clause in an existence check?
Nigel Rivett
www.mindsdoor.net

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #6
You're absolutely right- it doesn't make sense to use count and exists.

I don't know another way to check the existence of a column on a table-
perhaps you can suggest another function?
Thanks for the feedback :).

Jul 23 '05 #7
if not exists (select * from information_schema.columns where TABLE_NAME
= @tblname and COLUMN_NAME = @colname and TABLE_SCHEMA = @user)
begin

Nigel Rivett
www.nigelrivett.net

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #8
Dave (dh******@gmail.com) writes:
You're absolutely right- it doesn't make sense to use count and exists.

I don't know another way to check the existence of a column on a table-
perhaps you can suggest another function?


IF col_length('tbl', 'col') IS NULL
-- Column does not exist
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Laurence Breeze | last post by:
Is it possible to add a column to a table using the "alter table" statement and specify where in the sequence of columns the new column sits. If not is there any way to alter the order of columns...
2
by: me | last post by:
I would like to add an Identity to an existing column in a table using a stored procedure then add records to the table and then remove the identity after the records have been added or something...
1
by: Matik | last post by:
Hello, I need to change collation in my database (more databases acctualy). Therefore, I wanted to make a script, which will do it at one more time. I already have a cursor, updating...
10
by: BuddhaBuddy | last post by:
Platform is DB2/NT 7.2.9 The table was created like this: CREATE TABLE MYTEST ( MYTESTOID bigint not null primary key, FK_OTHEROID bigint not null references other, FK_ANOTHEROID bigint not...
0
by: Gianfranco | last post by:
Hi, I'm not familiar at access and at VBA either, so I need some help or at least some hint please. I have table "availabledrivers", coming from a query to the table "drivers". Then I have a table...
5
by: Mike L | last post by:
Hello all I'm trying to migrate a BE from Access to SQL Server. I've been making changes to the Access BE from the FE with SQL statements, and want to do the same with the BE in SQL Server. ...
2
by: RamaKrishna Narla | last post by:
In MS SQL Server, I have the following tables with some data in it. create table table1 ( column1 varchar(32), column2 int not null, column10 varchar(255), ..... primary key (column1,...
4
by: Brian Wotherspoon | last post by:
Hi all, I'm using SQL Server 2000 SP3 to store data for real time transaction processing. I have set up replication to another server using a push subscription to give me immediate backup. ...
1
by: vasilip | last post by:
I'm testing out db2 for a project I'm starting that requires proper xml support and I can't seem to get both xml and spatial data to work well in the same table. Once having created a table...
5
by: Giacomo | last post by:
Hi, I’ve the following error message: --------------- ALTER TABLE . ALTER COLUMN varchar(10) Go Server: messaggio 4929, livello 16, stato 1, riga 1
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.