473,802 Members | 2,026 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Beginner question: find or create function

I have a table with two columns: siteID (int primary key) and siteName
(varchar(50) unique constraint).

I am completely new to databases and UDFs and would like to write a
function that looks for a particular siteName and returns the siteID.
If the siteName is not found then it would create a record and return
that record's siteID.

I am pretty sure there is a standard way of doing it and have been
looking for examples, but have yet to find anything on Google.

If anyone could point me in the right direction I would be very
grateful - I am still looking and will reply if I find anything.

Many thanks

Jon

Jan 18 '07 #1
6 2700
Hi Jon,

Are you sure you really need to use UDF? In UDFs you can only insert in
table variables that are local to the function. However, using a stored
procedure it works just fine. Here is an example:

CREATE PROCEDURE GetSiteID (
@siteName AS VARCHAR(50))
AS
DECLARE @siteID INT

IF Exists(SELECT 1
FROM MySitesTable
WHERE siteName = @siteName)
BEGIN

-- Site exists: get the site Id
SELECT @siteID = siteID
FROM MySitesTable
WHERE siteName = @siteName

END
ELSE
BEGIN

-- Site does not exist: insert a new site
INSERT INTO MySitesTable (
siteName )
VALUES (
@siteName )

-- Get the new site ID
SELECT @siteID = @@IDENTITY

END

RETURN (@siteID)

GO

I am assuming here you have your siteID column defined as identity and it
will automatically generate the siteID number. You can return the new siteID
in different ways based on how you need to use it. It could be an output
parameter of the SP, using SELECT, or RETURN. Here is how you use it with
RETURN as I wrote it:

DECLARE @siteID INT

EXEC @siteID = GetSiteID 'Test'

SELECT @siteID

Regards,

Plamen Ratchev
http://www.SQLStudio.com

"jrpfinch" <jr******@gmail .comwrote in message
news:11******** *************@l 53g2000cwa.goog legroups.com...
>I have a table with two columns: siteID (int primary key) and siteName
(varchar(50) unique constraint).

I am completely new to databases and UDFs and would like to write a
function that looks for a particular siteName and returns the siteID.
If the siteName is not found then it would create a record and return
that record's siteID.

I am pretty sure there is a standard way of doing it and have been
looking for examples, but have yet to find anything on Google.

If anyone could point me in the right direction I would be very
grateful - I am still looking and will reply if I find anything.

Many thanks

Jon

Jan 18 '07 #2
On 18.01.2007 14:51, Plamen Ratchev wrote:
Are you sure you really need to use UDF? In UDFs you can only insert in
table variables that are local to the function. However, using a stored
procedure it works just fine.
Agreed.
Here is an example:

CREATE PROCEDURE GetSiteID (
@siteName AS VARCHAR(50))
AS
DECLARE @siteID INT

IF Exists(SELECT 1
FROM MySitesTable
WHERE siteName = @siteName)
BEGIN

-- Site exists: get the site Id
SELECT @siteID = siteID
FROM MySitesTable
WHERE siteName = @siteName

END
ELSE
BEGIN

-- Site does not exist: insert a new site
INSERT INTO MySitesTable (
siteName )
VALUES (
@siteName )

-- Get the new site ID
SELECT @siteID = @@IDENTITY

END

RETURN (@siteID)

GO
There's a more efficient option:

SELECT @siteID = siteID
FROM MySitesTable
WHERE siteName = @siteName

IF @siteID IS NULL
BEGIN
INSERT INTO MySitesTable ( siteName )
VALUES ( @siteName )
SET @siteId = SCOPE_IDENTITY( )
END

return @siteID
First, use the SCOPE_IDENTITY( ) in order to avoid concurrent sessions to
interact with each other. Then start out with the SELECT and see
whether you got something. That way you avoid the overhead of first
checking for existence. Also, it might actually happen that the check
suceeds and when you want to retrieve the value it's gone.

Note also that you need something like SELECT MIN(siteid) if siteName is
not unique.

My 0.02EUR

robert
Jan 18 '07 #3
Hi Robert,

I agree on the performance note and use of SCOPE_IDENTITY( ), I was just
trying to simplify things and illustrate better the steps. But if there is
concurrent activity this better be in a transaction, as even in your example
if siteID is NULL by the time you insert it there might be another insert
with the same siteName and the statement will result in error. And not an
issue with uniqueness for siteName as it was indicated there is unique
constraint on it.

Regards,

Plamen Ratchev
http://www.SQLStudio.com

"Robert Klemme" <sh*********@go oglemail.comwro te in message
news:51******** *****@mid.indiv idual.net...
On 18.01.2007 14:51, Plamen Ratchev wrote:
>Are you sure you really need to use UDF? In UDFs you can only insert in
table variables that are local to the function. However, using a stored
procedure it works just fine.

Agreed.
Here is an example:

CREATE PROCEDURE GetSiteID (
@siteName AS VARCHAR(50))
AS
DECLARE @siteID INT

IF Exists(SELECT 1
FROM MySitesTable
WHERE siteName = @siteName)
BEGIN

-- Site exists: get the site Id
SELECT @siteID = siteID
FROM MySitesTable
WHERE siteName = @siteName

END
ELSE
BEGIN

-- Site does not exist: insert a new site
INSERT INTO MySitesTable (
siteName )
VALUES (
@siteName )

-- Get the new site ID
SELECT @siteID = @@IDENTITY

END

RETURN (@siteID)

GO

There's a more efficient option:

SELECT @siteID = siteID
FROM MySitesTable
WHERE siteName = @siteName

IF @siteID IS NULL
BEGIN
INSERT INTO MySitesTable ( siteName )
VALUES ( @siteName )
SET @siteId = SCOPE_IDENTITY( )
END

return @siteID
First, use the SCOPE_IDENTITY( ) in order to avoid concurrent sessions to
interact with each other. Then start out with the SELECT and see whether
you got something. That way you avoid the overhead of first checking for
existence. Also, it might actually happen that the check suceeds and when
you want to retrieve the value it's gone.

Note also that you need something like SELECT MIN(siteid) if siteName is
not unique.

My 0.02EUR

robert

Jan 18 '07 #4

Please don't top post.

On 18.01.2007 21:47, Plamen Ratchev wrote:
I agree on the performance note and use of SCOPE_IDENTITY( ), I was just
trying to simplify things and illustrate better the steps.
With all due respect, don't you think my solution is simpler or at least
as simple? There's not really a difference in complexity between
SCOPE_IDENTITY( ) and @@IDENTITY and your solution needs one more SQL
statement. :-)
But if there is
concurrent activity this better be in a transaction, as even in your example
if siteID is NULL by the time you insert it there might be another insert
with the same siteName and the statement will result in error.
Of course all this must be in a transaction - how would you execute the
code without TX at all, especially since it's in a stored procedure?
And not an
issue with uniqueness for siteName as it was indicated there is unique
constraint on it.
Ah, thanks! I hadn't seen that.

Regards

robert
Jan 19 '07 #5
Many thanks for you help. After further research, stored procedures do
seem the way forward. Both your solutions are better than by first-go
hacky solution.

Jon

Jan 19 '07 #6
Hi Robert,

Like I said I do agree with you. As for the complexity I was just referring
to taking the extra step in order to illustrate the process, not the using
of SCOPE_IDENTITY( )... :)

Thanks!

Plamen Ratchev
http://www.SQLStudio.com
Jan 19 '07 #7

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

Similar topics

15
1936
by: PhilB | last post by:
Hello experts, I am a complete beginner in C++ (although I know C). I am trying to compile the code below, and I get the following error. Can anyone explain to me my mistake? Thanks! PhilB myprog2.cpp: In method `Line::Line (Point, Point)': myprog2.cpp:32: no matching function for call to `Point::Point ()'
1
2628
by: Mike Malter | last post by:
I am just starting to work with reflection and I want to create a log that saves relevant information if a method call fails so I can call that method again later using reflection. I am experimenting a bit with what I need to do this and have the following code snippet. But first if I pass the assembly name and type to Activator.CreateInstance() it always fails. However if I walk my assembly and get a type value, the call to...
8
7599
by: Shamrokk | last post by:
My application has a loop that needs to run every 2 seconds or so. To acomplish this I used... "Thread.Sleep(2000);" When I run the program it runs fine. Once I press the button that starts the looping function the window becomes unmovable and cannot close under its own direction (the upper right "close 'X'") My first attempt to solve the problem was to have the looping function execute as its own thread, the idea being this would...
4
1803
by: anonymous | last post by:
Hi Folks, I have a form with two Dropdown list boxes, which get loaded with data from Database. DropDownList1 gets data from Table1 and DropDownList2 gets data from Table2 Table1 has a parent child relationship with Table2 ( has a foreign key to Table1)
9
2030
by: me | last post by:
Hi All, I am new to Classes and learniing the ropes with VB.NET express Here's my question - say I have a want to manage a list of books. Each book has an Author, Title and ISBN Now, I am used to using Arrays so I would normally do something like this: Set an array up during the init routine (called from form_load) say of
15
2323
by: Notre Poubelle | last post by:
Hello, I have a large legacy MFC application. As is typical, there is an executable along with several MFC DLLs. One of these DLLs is created by staticly linking in many libraries resulting in one very large DLL that has the bulk of the code. I've downloaded the MFCWinFormsSample.EXE and have noticed that the main app could stay as a native executable (i.e. no CLR support) whereas the various ..DLLs can be marked as having CLR...
4
2663
by: Ranginald | last post by:
Sorry for the simple question but thanks in advance: My goal is to create reusale code for a web app in C#. I have written the code already as a windows app but here is where I am confused: To keep it really easy let's say this is the code: function addition(int, int); int X;
11
1211
by: bambam | last post by:
Would someone like to suggest a replacement for this? This is a function that returns different kinds of similar objects, depending on what is asked for. PSP and PWR are classes. I don't really want to re-write the calling code very much: I'm just wondering if the function can be replaced with some kind of OOP pattern. def Device(DeviceType): if DeviceType=='PSP': return PSP() elif DeviceType=="Power Supply"
22
18154
by: ddg_linux | last post by:
I have been reading about and doing a lot of php code examples from books but now I find myself wanting to do something practical with some of the skills that I have learned. I am a beginner php programmer and looking for a starting point in regards to practical projects to work on. What are some projects that beginner programmers usually start with? Please list a few that would be good for a beginner PHP programmer to
0
9699
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9562
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10538
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10285
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10063
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9115
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6838
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2966
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.