How To Return True If A Sql Row Exists

Mar 10, 2008

 Hi all,
 I am trying to access a sql database and if the userid exists in the database to the let me query another statement within an IF block to check another statement within the data, however I cannot seem to get it to work. I need something like sql.row.count != 0 within  the 2nd IF statement below. What can I do?

Thanks in advance.
Jason

 
  
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void btnStart_Click(object sender, ImageClickEventArgs e)
    {
        if (Session["userid"] == null)
        {
            Response.Redirect("accessdenied.aspx");
        }
        else
        {
            //Response.Redirect("page1.aspx");
            SqlConnection objConnect = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);

            objConnect.Open();
            SqlCommand cmd = new SqlCommand("SELECT user_id FROM users WHERE user_id = '" + Session["userid"] + "'");

            if (cmd == true)
            {
                Response.Redirect("page5.aspx");
            }

            objConnect.Close();
        }
    }
}


 

View 7 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: If Not Exists Returning False When Should Be True

Jul 3, 2014

Actually title should be returns true when should false.

I want to check a table to see if a record already exists, if it doesn't then insert it, else do nothing:

IF NOT EXISTS
(SELECT 1 FROM Table1 WHERE col1 = 'Test')
BEGIN
INSERT INTO Table1 (col1) VALUES ('Test')
END

The value 'Test' is already in the database yet, the code is saying it's not and trying to insert it, resulting in duplicate key errors.

View 9 Replies View Related

Return True False

Mar 20, 2008

Hi,
I need to check the existence of a row in a table.
So i am using an if condition
like
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER PROCEDURE [dbo].[CheckNOAStages]
@NOAID int,
@StageCode nchar(20)
AS
BEGIN

SET NOCOUNT ON;
Declare @Count int
Select @Count =Count(NOAId) from NOAStages where NOAID=@NOAID and StageCode=@StageCode
if (@Count>0)
Begin
return 1
end
else
begin
return 0
end


END

The stored proc is executing but on the Data Access Layer
I have this
Boolean exists = Convert.ToBoolean (Execute.ExecuteReader(spCollection, dbSQL));

Some how I am always getting false . How can I fix this?
Thanks

View 7 Replies View Related

How Transaction Return True And False

Jun 10, 2008

Sir

I want to Return 1 and 0 after update , delete , Insert statement

IF Records Effected Return 1 else return 0

Pls help me out .........Sir

Yaman

View 4 Replies View Related

How To Write A Function That Will Return True If User Is In A Certain Role?

Jul 20, 2005

I have a SQL database with an Access front end. In the database Ihave a read only and a read write role. When a read only user opensthe database I want all the fields on the form to be locked so thatthe user will not try to change data and get an error from the server.Right now I am doing that with a table. But it's a hassle to have tomaintain a table when if I could answer the question is the currentlylogged in user in the read write role?My server is running SQL Server 2000. So I was wondering if I couldwrite a function to do this? The function would take the role beingchecked as a text parameter and return true if the currently logged inuser is in that role or false if he/she isn't.

View 1 Replies View Related

Multiple CASE Statements - Three Fields To Be True In Order To Return Y

Feb 19, 2014

How do I properly write a CASE statement for the following business logic:

I want three of the following fields to be true in order to return 'Y'.

For example:

If field name 'Accepted' = 1 AND field 'StepNo' = '1' and field 'Visit' = 'V1'

Otherwise, I want it to return 'N'.

I have tried the following code below and it is not working.

, CASE WHEN Accepted = '1' AND StepNo ='1' AND Visit ='V1'
THEN 'Y' ELSE 'N' END AS 'StatusQ (Col N)'

View 2 Replies View Related

Analysis :: Cube Dimension With Bool Filter Shows (blank) And True Instead Of False And True?

Jul 31, 2015

I have a cube that has a Dimension set up with several values some of which are bools. While Browsing in Excel or SSMS, two new values, when used as a filter shows (All) (Blank) and (True) for selections instead of (All) (True) and (False). 

View 2 Replies View Related

Return Value For NOT EXISTS

Oct 24, 2006

Hi

I frequently use the "If NOT EXISTS (Select ...) Insert ..." statement and would like to display a message to the user after the execution of the statement to say whether the Insert was or wasn't executed. Is there a way to get SQL to return a value that will tell me if the Insert was carried out or not? If not, perhaps you know of some other efficient way of handling this situation.

Regards

Neil

View 6 Replies View Related

RETURN Of IF NOT EXISTS INSERT Statement

Feb 20, 2006

Hi @ all

I'm using MSSQL and PHP.
I've got the following sql statement:

$msquery = IF NOT EXISTS (SELECT SerienNr FROM tbl_Auftrag a WHERE a.SerienNr='PC8') INSERT INTO tbl_Auftrag (BMS_AuftragsNr, SerienNr, AuftraggNr, Zieltermin, Kd_Name) VALUES ('455476567','PC8','1','2006-3-2','Fritz')

The Statement itself works fine, but i've got a problem getting a return value whether the insert has succeed, or not. :confused:
mssql_query() always returns true if there occured no error in the statement. But i need to know if the insert procedded or not.
I tried:

$result = mssql_query($msquery);
$succeed = mssql_rows_affected ($result);

And:

$result = mssql_query($msquery);
$succeed = mssql_num_rows($result);

to get the rows, affected by the statement, but both return:

supplied argument is not a valid MS SQL-Link resource

Anyone an idea?

View 2 Replies View Related

If Username Exists, Return Try Again Otherwise Write To Db

Sep 9, 2007

I am a SQL newbie trying to create a registration page. The registration data is stored in "tblUsers," and the username is stored in the field named "UID" -- which is the primary key. If the user enters a username that already exists in the database, I want to return the "That username already exists" message and keep them on the registration page. If the username doesn't exist, I want to write all their registration info to the database.

I tried the code below using both an existing username and then using a username that didn't exist. Both times I got the "that username already exists" error message on the top of the confirmation page, and the record was not written to the database.

I also tried changing the "If objRec.RecordCount <> 0" to "If objRec.RecordCount >0" I got it to write to the database if the username didn't exist, but if the username did exist, I got the microsoft error '80040e14' (The changes you requested to the table were not successful because they would create duplicate values...)

Thanks for any help.


<%
SQLCmd = "SELECT UID From tblUsers WHERE UID = " & "'" & UID & "'"
Set objRec = objConn.Execute(SQLCmd)
If objRec.RecordCount <> 0 Then
Response.write "That username already exists"
Else
SQLCmd = "INSERT INTO tblUsers"
SQLCmd = SQLCmd & " (FIRSTNAME, LASTNAME, UID, PWD, STREET, CITY, STATE, ZIP, EMAIL, PHONE, FAX, PHYSICIAN, SPECIALTY, OTHER) "
SQLCmd = SQLCmd & " VALUES ('" & firstname & "',"
SQLCmd = SQLCmd & "'" & lastname & "',"
SQLCmd = SQLCmd & "'" & UID & "',"
SQLCmd = SQLCmd & "'" & PWD & "',"
SQLCmd = SQLCmd & "'" & street & "',"
SQLCmd = SQLCmd & "'" & city & "',"
SQLCmd = SQLCmd & "'" & state & "',"
SQLCmd = SQLCmd & "'" & zip & "',"
SQLCmd = SQLCmd & "'" & email & "',"
SQLCmd = SQLCmd & "'" & phone & "',"
SQLCmd = SQLCmd & "'" & fax & "',"
SQLCmd = SQLCmd & "'" & physician & "',"
SQLCmd = SQLCmd & "'" & specialty & "',"
SQLCmd = SQLCmd & "'" & other & "')"
Set objRec = objConn.Execute(SQLCmd)
End If
%>

View 14 Replies View Related

Return Rows Only If More Than 1 Row Of The Same Policy Number Exists?

Sep 25, 2007

I have a policy table which has policyNumbers and createDate. I need to retrieve all rows where createDate is between 2 dates and there is more than 1 row with the same policy number. I cannot figure out the SQL to return all policy number rows if there are more than 1 row with the policy. Most policies number will be in the table once. I need the others.

Thanks for suggestions.

View 1 Replies View Related

SQL Server 2012 :: How To Return User-defined Row When A Record Doesn't Exists

Dec 29, 2014

What I want to do is return a row of data when my query doesn't return a record. I have two tables:

CREATE TABLE dbo.abc(
SeqNo smallint NULL,
Payment decimal(10, 2) NULL
) ON PRIMARY

[Code] ....

So when I run the following query:

SELECT 'abc' + '-' + CAST(SeqNo AS VARCHAR) + '-' + CAST(Payment AS VARCHAR) FROM abc WHERE SeqNo = 1
UNION
SELECT 'def' + '-' + CAST(SeqNo AS VARCHAR) + '-' + CAST(Payment AS VARCHAR) FROM def WHERE SeqNo = 1
abc-1-200.00
abc-1-500.00

As you can see since 1 doesn't exists in table 'def' nothing is returned as expected. However, if a row isn't returned I want to be able to enter my own row such as

abc-1-200.00
abc-1-500.00
def-0-0.00

View 4 Replies View Related

Problem With Isnull. Need To Substitute Null If A Var Is Null And Compare It To Null And Return True

Sep 20, 2006

Hey. I need to substitute a value from a table if the input var is null. This is fine if the value coming from table is not null. But, it the table value is also null, it doesn't work. The problem I'm getting is in the isnull line which is in Dark green color because @inFileVersion is set to null explicitly and when the isnull function evaluates, value returned from DR.FileVersion is also null which is correct. I want the null=null to return true which is why i set ansi_nulls off. But it doesn't return anything. And the select statement should return something but in my case it returns null. If I comment the isnull statements in the where clause, everything works fine. Please tell me what am I doing wrong. Is it possible to do this without setting the ansi_nulls to off??? Thank you

set ansi_nulls off


go

declare

@inFileName VARCHAR (100),

@inFileSize INT,

@Id int,

@inlanguageid INT,

@inFileVersion VARCHAR (100),

@ExeState int

set @inFileName = 'A0006337.EXE'

set @inFileSize = 28796

set @Id= 1

set @inlanguageid =null

set @inFileVersion =NULL

set @ExeState =0

select Dr.StateID from table1 dR

where

DR.[FileName] = @inFileName

AND DR.FileSize =@inFileSize

AND DR.FileVersion = isnull(@inFileVersion,DR.FileVersion)

AND DR.languageid = isnull(@inlanguageid,null)

AND DR.[ID]= @ID

)

go

set ansi_nulls on

View 3 Replies View Related

Is It True?

Jul 7, 2006

Microsoft E-Learning products are currently available for purchase only within North America at this time

Jezz, bad luck I am currently living in Spain...

View 1 Replies View Related

In A Where How Can I Use True Or False

Oct 20, 2007

I have a stored procedure that has a boolean (bit) field passed to it (@emailcontract). If a user checks the check box on the webform I would like my where to return only the records where the email_contract column is true. If they don't check the check box I would like it to return records where email_contracts is true or false.
What would my where cluse look lile for this?

View 4 Replies View Related

If True GO ON Else END PACKAGE

Oct 16, 2006

I am designing a package performing some data imports from a text file to some tables, passing by a temporary table.
My specific requirements are:
initially the package checks if the input file exists, if it doesn't it will not continue.I have implemented this with a Script Task, and if the
file doesn't exist I fail the all package (Dts.TaskResult =
Dts.Results.Failure). Is this the right way?

after copying the data into a temporary table, it checks via SQL if some conditions are verified, if not it will not continue.I would have liked to do it via an SQL Task, but I don't know how to stop the package if the conditions are not what expected. Anybody can help?

Thank you.

View 2 Replies View Related

True False

May 13, 2007

All



Can I ask what data type i use for a true false response (Boolean) in my table?



Thanks



Gibbo

View 1 Replies View Related

List All Of A Set Of Rows When Only One Row Is True

May 3, 2007

This is stupid, I used to be able to do this all the time by mistake now I can't do it on purpose
I want to be able to return a full list of matching records when only one is true
LikeRow 1, ID_1, falseRow 2, ID_1, falseRow 3, ID_1, trueRow 4, ID_2, falseRow 5, ID_2, trueRow 6, ID_2, false
I currently getRow 3, ID_1, trueRow 5, ID_2, true
 
 
 
 

View 3 Replies View Related

What Is The Trusted_Connection=true Parameter?

Feb 9, 2004

what does this imply Trusted_Connection=true parameter in the Connection String signify?
Secondly how can I make users with Windows Authentication Login to work in SQL Server Connection String?


Thanks in advance,

Neeraj.

View 1 Replies View Related

Trunc. Log On Chkpt. Is True

Mar 17, 2006

hi

I just created a DB , & ran sp_dboption , it showed me that the trunc. log on chkpt. is true .....

What if i set the recovery model of this DB to full , would I be able to recover the DB to a specific point in time ,
or since trunc. log on chkpt. is true.. I would not be able to collec the transaction log backups ???

Cant understand this concept , need some link to read this stuff ....


Thanks

View 1 Replies View Related

Job Ends Successfully Even When It's Not True

Apr 23, 2008

Hi,
we've got this problem with some particular jobs: they look as they
ran correctly, but actually they didn't made it all through their
duties.
The problem is that this job is calling a sequence of DTS, where there
is a DTS with an ActiveX control which modifies another DTS before
launching and some other tasks: the error happens there, .
Launched from the DTS we get the error, from the job no...any idea how
we could get the correct job information?
Thank you
Daniele

View 5 Replies View Related

How To Change From True Or False To 1 Or 0

Oct 29, 2007



Hello

I am exporting an SQL Server table to a comma delimited text file. The values of Columns defined as Bit are exported as "True" or "False", but I would like that in the file appear 1 or 0 instead (with no surrounding double quotes). How can I acomplish that?

I tried using a Transformation and convert to single byte unsigned integer, but True values are exported as "255" and False values as "0". Why?

Thanks a lot.

View 1 Replies View Related

How To Set This Parameter AlwaysUseDefaultCodePath=TRUE

Sep 24, 2007

Hello all,
I am trying to migrate date from Oracle 10g to SQL serve 2005 during the data transformation I get the following error



Messages

Warning 0x80202066: Source - SERVICE [1]: Cannot retrieve the column code page info from the OLE DB provider. If the component supports the "DefaultCodePage" property, the code page from that property will be used. Change the value of the property if the current string code page values are incorrect. If the component does not support the property, the code page from the component's locale ID will be used.
(SQL Server Import and Export Wizard)




I searched internet and solution seems to be setting AlwaysUseDefaultCodePath="TRUE"


But where do you do this ?


I found this too: It's on the Properties tab of the OLE DB Source in Custom Properties section.


But still do not know where to go to set this parameter

Please help

View 4 Replies View Related

Trying To Insert Checkbox True/false Into Db

Aug 15, 2005

Hi there, I've tried googling this (and looking at the many questions on the forum :) but I've not managed to find a decent tutorial / guide that describes a method for using checkboxs to insert true/false flags in a MS SQL db.  The db field i'm setting has type set to "bit", is this correct?  And secondly (its been a long day!) I just cant figure out the code to assign the bit 1 or 0 / true or false. This is what I've got so far but it's not working........Function InsertProduct(ByVal prod_code As String, ByVal prod_name As String, ByVal prod_desc As String, ByVal prod_size As String, ByVal prod_price As String, ByVal prod_category As String, ByVal aspnet As Boolean) As Integer             Dim connectionString As String = "server='server'; user id='sa'; password='msde'; Database='dbLD'"             Dim sqlConnection As System.Data.SqlClient.SqlConnection = New System.Data.SqlClient.SqlConnection(connectionString)                 Dim queryString As String = "INSERT INTO [tbl_LdAllProduct] ([prod_code], [prod_name], [prod_desc], [prod_size], [prod_price], [prod_category],[aspnet]) VALUES (@prod_code, @prod_name, @prod_desc, @prod_size, @prod_price, @prod_category, @aspnet)"             Dim sqlCommand As System.Data.SqlClient.SqlCommand = New System.Data.SqlClient.SqlCommand(queryString, sqlConnection)                 sqlCommand.Parameters.Add("@prod_code", System.Data.SqlDbType.VarChar).Value = prod_code             sqlCommand.Parameters.Add("@prod_name", System.Data.SqlDbType.VarChar).Value = prod_name             sqlCommand.Parameters.Add("@prod_desc", System.Data.SqlDbType.VarChar).Value = prod_desc             sqlCommand.Parameters.Add("@prod_size", System.Data.SqlDbType.VarChar).Value = prod_size             sqlCommand.Parameters.Add("@prod_price", System.Data.SqlDbType.VarChar).Value = prod_price             sqlCommand.Parameters.Add("@prod_category", System.Data.SqlDbType.VarChar).Value = prod_category                 If chkAspnet.Checked = True Then                sqlCommand.Parameters.Add("@aspnet","1")             Else                sqlCommand.Parameters.Add("@aspnet","0")             End If                     Dim rowsAffected As Integer = 0             sqlConnection.Open             Try                 rowsAffected = sqlCommand.ExecuteNonQuery             Finally                 sqlConnection.Close             End Try             Return rowsAffected         End Function             Sub SubmitBtn_Click(sender As Object, e As EventArgs)            If Page.IsValid then                InsertProduct(txtCode.Text, txtName.Text, txtDesc.Text, ddSize.SelectedItem.value, ddPrice.SelectedItem.value, ddCategory.SelectedItem.value, aspnet.value)                Response.Redirect("ListAllProducts.aspx")            End If    End SubAny help would be appreciated or links to tutorials.ThanksBen

View 2 Replies View Related

Trusted_connection=true, Login '(null)'

Mar 31, 2006

When accessing a web application from an intranet....
And the web app tries to make a connection to a 'SQL Server' using the sqlconnection where does ASP.NET grab user credentials?
My webpage displays web security.principal.windows.getcurrent = domainUser  (displays the correct information).
But the connection to sql says Null.  Where is ASP.NET grabbing (retrieving) this information from?
Thanks,

View 3 Replies View Related

OR-statement Returns True CHARINDEX Instead Of Name LIKE

Jun 11, 2013

I have this OR in a simple query:

Code:
DECLARE @searchString nvarchar(100)
SET @searchString = 'sample'
SELECT TOP(1) * FROM user
WHERE (user.identity LIKE @searchString OR
CHARINDEX(@searchString, user.firstname + ' ' + user.lastname) > 0)
PS: Handwritten...

If I pass in a searchString that matches the Identity and a different users lastname, this query will return the user with the lastname-match (which is wrong in my eyes, it should have matched the Identity first, then returned that row [Identity is a Primary key, indexed non-clustered]).

I've tried various things:
Removing LastName: (CHARINDEX(@searchString, user.firstname + ' ') > 0), then the returned row is from a matching identity, due to the lastname of a user was a match, but lastname was removed...so :P
Flipping the conditions around
Adding/removing paranthesis... without any luck.

Is there some option somewhere, to force the OR statement to return on the first true condition. I've always thought OR-statements (in a computer that is) breaked and returned true on the first true condition it found (from left to right, not bother to check the rest of the conditions...)?Or do I have to rewrite the query, with an IF, checking if the @searchString is a valid identity-format, if it is, query on the identity, if not query on the username...?

View 12 Replies View Related

Send Mail True Sproc

Jan 30, 2004

Hi all,

I have a database filled with contracts, suppliers and administrators who administrates those contracts.

I want to make a sproc that checks the difference between the expiration_date and the current date(in months). the sproc compares this output with a given period in the contracts-table. when the output <= the given period ---> send mail to the administrator with info about the contract. and that the contract will be expired in X months.

Having a Sproc that only gets the info from the tables and compares this info is no problem, but to let the sproc send an email to the admin whose email-adress also comes from a table is a little bit to tricky for me.

I have searched the internet but i can't figure it out.

If anyone knows where I can get more info about this subject please be so kind and let me know, or anything that could help me around for the moment.

PS. I'm using SQL server 2000

Thnx in advance

StylizIt

View 12 Replies View Related

SQL Server Thinks True Is A Column Name

May 12, 2007

Hello SQL Server Experts,

I'm upgrading an application that uses a VBScript/ASP front-end and MS Access Backend. The application has many points expecting fields to be true or false..

E.g. SELECT * FROM MyTable WHERE Active=True

However, since SQL Server requires 0 or 1 for bit fields, this query keeps failing. SQL Server (2005 Express) thinks True is a column name and is not automatically converting "True" to 1.

It would be so difficult to re-write the application to do this at the VB level, is there a way to make SQL server do this conversion automatically ?

Thanks for any assistance available.

Sunny

View 1 Replies View Related

What Is The True Definition Of Catalog Table?

Jul 23, 2005

We hear about catalog table in documentation but is this the same asdatabase schema?What is the definiation of catalog table?What does it pertain to?Thanks--Message posted via http://www.sqlmonster.com

View 1 Replies View Related

Multiple Web Viewers And AsyncRendering True

Nov 1, 2007

I have multiple viewers on a web page and initialy would like AsyncRendering = true on all viewers, so I can have the loading message. Once the user drill-through, I hide all other viewers and change to AsyncRendering = false, so the autosizing will work.
But, with AsyncRendering = true (in code behind):
private void SetDominateViewerProperties(ReportViewer rptViewer)
{
rptViewer.AsyncRendering = false;
rptViewer.ShowToolBar = true;
rptViewer.ZoomPercent = 100;
rptViewer.Visible = true;
}
private void SetDefaultViewerProperties(ReportViewer rptViewer)
{
rptViewer.AsyncRendering = true;
rptViewer.ShowToolBar = true;
rptViewer.ZoomPercent = 100;
rptViewer.Visible = true;
}
I have only one viewer showing, even though, I can see in debug that all viewers are set to visible. In SetDefaultViewerProperties, I change rendering to false, I get multiple viewers. Are there combinations of property values I need to set?

View 1 Replies View Related

Can't Aquire Connections Because OfflineMode Is True

Aug 21, 2007

I am designing a SSIS package (source=Flat files,, destination =OLEDB) which is executing fine on my system but when I try to execute it on Server 2003 (x64)
it says Error: The AcquireConenction method call to connection manager "name of conn" failed with error code 0xC0014019 and
it says can't Aquire Connections because OfflineMode is true, while as I checked several times while saving the package it is set to false...

View 7 Replies View Related

SaveCheckpoints=True Affects Recordset

Jun 16, 2006

I have a package that creates a recordset in a variable (Type=Object, Name=CountryTable).  The recordset is then picked up in a Script Task and loaded into a table using this code:

        Dim adp As New OleDb.OleDbDataAdapter
        dt = New DataTable

        adp.Fill(dt, Dts.Variables("CountryTable").Value)

It was working fine until I turned SaveCheckpoints ON.  Now it does not load any rows into the dt table. The dataflow task with the recordset destination ('CountryTable' variable) reports 10 rows in the pipeline.  If I turn SaveCheckpoints OFF, it fills the dt table OK.  If it cannot fill the dt table because of SaveCheckpoints being ON, shouldn't it give an error message?  Thanks.

Note: I have SP1 installed.

 

 

View 4 Replies View Related

SizeToReportContent Does Not Work When ShowToolBar=True

Jan 30, 2007

Requirement: Auto-sized report with toolbar, rendered in a ReportViewer in an ASP .NET 2 page.

As we all know the trick is SizeToReportContent = True AND AsynchRendering = False.

With these settings (and ShowToolBar = True) I am still getting scroll bars and no resizing!

I tried setting ShowToolBar=False and it worked! (but I have now lost the export capability).

When ShowToolBar=True the ReportViewer does not resize correctly (it seems to resize based on the width of the toolbar). It looks like the toolbar is rendered first and this width is used as the max. width for the SizeToReportContent.

Anyway my options are:
1) Toolbar "on" with weird resizing (ie scrollbars). This looks sloppy.
2) Toolbar off (no ability to export, which I need). Export is a requirement.
3) Hard code the size to something big enough to hold the report (welcome to 1986)

Anyone else see the same behavior or am I missing something?



View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved