Showing posts with label entering. Show all posts
Showing posts with label entering. Show all posts

Friday, February 24, 2012

checking to see if field value is unique

When entering a value into a SQL database is there a way to find out if that value has already been used in that field?

eg. If I were entering a last name into a field called "user_name" could I add some validation whereby the record couldn't be entered if someone else had already inserted that last name?You could:

1) use unique index in the user_name column to prevent duplicate values (i.e first name and last name into separate columns as well and target the index to the last name column). In this case DB throws an error if duplicate insert is tried.

2) you could also check the existence before inserting into table, something like:

IF (SELECT count(*) FROM MyTable WHERE Last_name='thename') > 0
BEGIN /*There is such last name already*/

END

ELSE /*There isn't such in the table*/

BEGIN

END|||Definitely create the unique contraint on the columns you don't want duplicated, as suggested. This will ensure that duplicate values cannot physically be entered.

You should also check for the existence before inserting into the table, so that you can gracefully capture the error and return user-friendly information back to the user. But, instead of the method suggested, you should try using EXISTS, which will stop processing as soon as the condition is met


IF EXISTS(SELECT NULL FROM MyTable WHERE Last_name='thename')
BEGIN /*There is such last name already*/
END

ELSE /*There isn't such in the table*/

BEGIN
END


Terri

Checking to see if a record exists before inserting

I can't seem to get this work. I'm using SQL2005

I want to check if a record exists before entering it. I just can't figure out how to check it before hand.

Thanks in advance.

Protected Sub BTNCreateProdIDandName_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles BTNCreateProdIDandName.Click' Define data objectsDim connAs SqlConnectionDim commAs SqlCommand' Reads the connection string from Web.configDim connectionStringAs String = ConfigurationManager.ConnectionStrings("HbAdminMaintenance").ConnectionString' Initialize connection conn =New SqlConnection(connectionString)' Check to see if the record existsIf comm =New SqlCommand("EXISTS (SELECT (BuilderID, OptionNO FROM optionlist WHERE (BuilderID = @.BuilderID) AND (OptionNO = @.OptionNO)", conn)Then'if the record is exists display this message. LBerror.Text ="This item already exists in your Option List."Else'If the record does not exist, add it. FYI - This part works fine by itself. comm =New SqlCommand("INSERT INTO [OptionList] ([BuilderID], [OptionNO], [OptionName]) VALUES (@.BuilderID, @.OptionNO, @.OptionName)", conn) comm.Parameters.Add("@.BuilderID", System.Data.SqlDbType.Int) comm.Parameters("@.BuilderID").Value = LBBuilderID.Text comm.Parameters.Add("@.OptionNO", System.Data.SqlDbType.NVarChar) comm.Parameters("@.OptionNO").Value = DDLProdID.SelectedItem.Value comm.Parameters.Add("@.OptionName", System.Data.SqlDbType.NVarChar) comm.Parameters("@.OptionName").Value = DDLProdname.SelectedItem.Value LBerror.Text = DDLProdname.SelectedItem.Value &" was added to your Option List."Try'open connection conn.Open()'execute comm.ExecuteNonQuery()Catch'Display error message LBerror.Text ="There was an error adding this Option. Please try again."Finally'close connection conn.Close()End Try End If End Sub

You need to execute the command to see if the record exists

comm =New SqlCommand("EXISTS (SELECT (BuilderID, OptionNO FROM optionlist WHERE (BuilderID = @.BuilderID) AND (OptionNO = @.OptionNO)", conn)
If cbool(comm.executescalar) then
 
|||

Hello my friend,

Try this in your SQL: -

IF EXISTS (SELECT 1 FROM optionlist WHERE BuilderID = @.BuilderID AND OptionNO = @.OptionNO)
BEGIN
RETURN 'ALREADY_EXISTS'
END
ELSE BEGIN
INSERT INTO [OptionList] ([BuilderID], [OptionNO], [OptionName])
VALUES (@.BuilderID, @.OptionNO, @.OptionName)

RETURN 'INSERT_OKAY'
END

Then execute this with Dim strResult as string = comm.ExecuteScalar(), not ExecuteNonQuery(), and check the strResult string to determine whether or not to display the LBerror text.

If you have any questions on this, please let me know.

Kind regards

Scotty

|||

Scotty,

Thanks for your help. I inserted the sql and I'm getting an error.

Incorrect syntax near ')'.
A RETURN statement with a return value cannot be used in this context.
A RETURN statement with a return value cannot be used in this context.

Line 81: Dim strResult As String = comm.ExecuteScalar()

Here is what I'm using.

I don't think I did this right..."Then execute this with Dim strResult as string = comm.ExecuteScalar(), not ExecuteNonQuery(), and check the strResult string to determine whether or not to display the LBerror text. "

Protected

Sub BTN1_Click(ByVal senderAsObject,ByVal eAs System.EventArgs)Handles BTN1.Click' Define data objectsDim connAs SqlConnectionDim commAs SqlCommand' Reads the connection string from Web.configDim connectionStringAsString = ConfigurationManager.ConnectionStrings("HbAdminMaintenance").ConnectionString' Initialize connection

conn =

New SqlConnection(connectionString)' Check to see if the record exists

conn.Open()

comm =

New SqlCommand("IF EXISTS (SELECT 1 FROM optionlist WHERE BuilderID = @.BuilderID AND OptionNO = @.OptionNO) BEGIN()Return 'ALREADY_EXISTS' End Else : BEGIN()INSERT INTO [OptionList] ([BuilderID], [OptionNO], [OptionName]) VALUES (@.BuilderID, @.OptionNO, @.OptionName)Return 'INSERT_OKAY'End)", conn)

comm.Parameters.Add(

"@.BuilderID", System.Data.SqlDbType.Int)

comm.Parameters(

"@.BuilderID").Value = LBBuilderID.Text

comm.Parameters.Add(

"@.OptionNO", System.Data.SqlDbType.NVarChar)

comm.Parameters(

"@.OptionNO").Value = DDLProdID.SelectedItem.Value

comm.Parameters.Add(

"@.OptionName", System.Data.SqlDbType.NVarChar)

comm.Parameters(

"@.OptionName").Value = DDLProdname.SelectedItem.ValueDim strResultAsString = comm.ExecuteScalar()

' I'm not sure what to do here. to get my error message to show.

LBerror.Text = strResult.ToString

conn.Close()

EndSub

|||

Option 1

=====

You can modify the query as

SELECT COUNT(*) as CountOfRecords

FROM

FROM optionlist WHERE BuilderID = @.BuilderID AND OptionNO = @.OptionNO

If the Count is greater than 0 then you know the record exists

Option2

=======

Wrap Scotty's SQL in a Stored procedure and call the SP. I would do this way. SPs are fast and adds alayer of abstraction.

|||

rednelo:

Scotty,

Thanks for your help. I inserted the sql and I'm getting an error.

Incorrect syntax near ')'.
A RETURN statement with a return value cannot be used in this context.
A RETURN statement with a return value cannot be used in this context.

Line 81: Dim strResult As String = comm.ExecuteScalar()

That because you added a set of parentheses following the BEGIN statement that Scott did not have in his supplied code. Remove those and you should have better luck.

|||

I removed the parentheses. Don't know how they got there...

I also tired putting it in a sproc, but I keep getting the same message.

Msg 178, Level 15, State 1, Line 3

A RETURN statement with a return value cannot be used in this context.

Msg 178, Level 15, State 1, Line 9

A RETURN statement with a return value cannot be used in this context.

|||

rednelo:

I removed the parentheses. Don't know how they got there...

I also tired putting it in a sproc, but I keep getting the same message.

Msg 178, Level 15, State 1, Line 3

A RETURN statement with a return value cannot be used in this context.

Msg 178, Level 15, State 1, Line 9

A RETURN statement with a return value cannot be used in this context.

A RETURN statement can only return an integer value. Scotty made a typo in his original code. Use SELECT instead:

SELECT 'ALREADY_EXISTS'

and

SELECT 'INSERT_OKAY'

|||

Those little typos can really cause one to pull their hair out! 4 hours later... We finally got it.

Thank-you for your help this works well.

checking object usage

Hello,
I'm entering an existing project that has hunderds of views.
I was wondering how can I get usage statistics for the views - which
ones are in use, which aren't, when were they in use, etc.
Thanks in advance,
R. GreenHi
sp_depends may tell you some information about where the view is used but it
does not always give you everything. Alternatively if you are using stored
procedures for access and have scripted them into text files you can
manually search for your views in them.
You may be able to get some idea of usage from analysing output from SQL
profiler, if you use stored procedures it will not be direct access i.e. you
will know if procedure X is called then it uses your view.
John
"Ronald Green" <zzzbla@.gmail.com> wrote in message
news:1145515140.295473.276370@.v46g2000cwv.googlegroups.com...
> Hello,
> I'm entering an existing project that has hunderds of views.
> I was wondering how can I get usage statistics for the views - which
> ones are in use, which aren't, when were they in use, etc.
> Thanks in advance,
> R. Green
>|||Hi John,
thanks for your quick reply.
I'm looking for information like how often a view is used / when was it
last used.
I can't run a profiler on this (production) server and there are hardly
any stored procedures used. Most of the views are used within DTS
packages
Thanks in advnace,
R. Green|||It's a good question, and one I've seen a few times recently. There
must be an app that actually profiles the access of objects instead of
the references in stored procedures. Please post if there is, otherwise
I think I'll write one, I mean we've got the execution plans from
profiler traces, so parsing them and building up some stats can't be
"that" big a deal.|||Hi Ronald
If you can't run profiler then it is unlikely that you will be allowed to
run any other tool. Sampling using say DBCC INPUTBUFFER will give you less
comprehensive information and therefore be less reliable. Either method may
miss a reference to a view used in a very rarely run report.
For the changes you intend to make you will need a test system and full
regression test to make sure that removing anything does not break your
system.
John
"Ronald Green" <zzzbla@.gmail.com> wrote in message
news:1145519552.676946.39150@.j33g2000cwa.googlegroups.com...
> Hi John,
> thanks for your quick reply.
> I'm looking for information like how often a view is used / when was it
> last used.
> I can't run a profiler on this (production) server and there are hardly
> any stored procedures used. Most of the views are used within DTS
> packages
> Thanks in advnace,
> R. Green
>|||hey,
so no 'last accessed date' on views, eh? :)|||Ronald Green (zzzbla@.gmail.com) writes:
> hey,
> so no 'last accessed date' on views, eh? :)
Right. No such thing.
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