Having Trouble With EXISTS
Sep 28, 2006
I'm trying to delete duplicate records from a table.
The table is full of "new" records that need to be added to the database
with some user input. Since the table is populated from multiple sources,
duplicate entries can be put in. I'd like to clean those out after each "run".
Here's what I have so far, but of course, it's not right:
create table tmpKickouts (
KICK_IDINTEGER IDENTITY,
PARTCODEVARCHAR(10),
KICKOUT_REASON INTEGER
)
INSERT INTO TMPKICKOUTS ( PARTCODE, KICKOUT_REASON)
SELECT 'ABC', 1
UNION ALL
SELECT 'ABC', 1
UNION ALL
SELECT 'ABC', 2
UNION ALL
SELECT 'DEF', 2
UNION ALL
SELECT 'GHI', 1
UNION ALL
SELECT 'GHI', 1
UNION ALL
SELECT 'GHI', 1
SELECT * FROM TMPKICKOUTS TK
WHERE NOT EXISTS (
SELECT MIN(KICK_ID) AS KICK_ID, PARTCODE FROM TMPKICKOUTS
WHERE PARTCODE IN (
SELECT DISTINCT PARTCODE FROM TMPKICKOUTS
WHERE KICKOUT_REASON=1)
AND KICKOUT_REASON=1 AND TMPKICKOUTS.KICK_ID=TK.KICK_ID AND TMPKICKOUTS.PARTCODE=TK.PARTCODE
GROUP BY PARTCODE)
AND KICKOUT_REASON=1
DROP TABLE TMPKICKOUTS
In this example, I'd want to delete records 2, 6, & 7
TIA
Mark
View 4 Replies
ADVERTISEMENT
Sep 20, 2006
Hi,
This is on Sybase but I'm guessing that the same situation would happen on SQL Server. (Please confirm if you know).
I'm looking at these new databases and I'm seeing code similar to this all over the place:
if not exists (select 1 from dbo.t1 where f1 = @p1)
begin
select @errno = @errno | 1
end
There's a unique clustered in dex on t1.f1.
The execution plan shows this for this statement:
FROM TABLE
dbo.t1
EXISTS TABLE : nested iteration.
Table Scan.
Forward scan.
Positioning at start of table.
It's not using my index!!!!!
It seems to be the case with EXISTS statements. Can anybody confirm?
I also hinted to use the index but it still didn't use it.
If the existence check really doesn't use the index, what's a good code alternative to this check?
I did this and it's working great but I wonder if there's a better alternative. I don't really like doing the SET ROWCOUNT 1 and then SET ROWCOUNT 0 thing. SELECT TOP 1 won't work on Sybase, :-(.
SET ROWCOUNT 1
SELECT @cnt = (SELECT 1 FROM dbo.t1 (index ix01)
WHERE f1 = @p1
)
SET ROWCOUNT 0
Appreciate your help.
View 3 Replies
View Related
Feb 16, 2004
I just got finished developing the company intranet site and thinking that everything was working I boasted about how good it was by getting my boss to login and submit a new job to the db (new job, its a work management app) while i did the same, the pland was to hit the submit button at the same time. He would send one to be read by me and I would send one to be read by him. We both hit submit and the following happened.
The db has somehow fused the two into one. I thought maybe we were to accurate in hitting the submit button together. But I even gave a five second delay between and for some reason the job is being overriden by one user tor the other. In other words we are both sharing the same jobid. I thought this could never happen with sql server supposing that it would lock one request until another was completed and vice versa. But I'm so new to this that I'm just so naieve to think that the db would do this for you. Problem is I'm about to move on and I can't leave the app in this state. Can anyone point to some articles or give some suggestions has to my situation. Most desperately in need!!
Thanks in advance
View 11 Replies
View Related
May 20, 2006
hello
i'm having touble getting my sp done. the problem is as follow..i've found an sp tokenize (which works fine) with the following signature:
CREATE PROCEDURE TOKENIZE (
S VARCHAR(10000),
DELIM CHAR(1))
RETURNS (
ID INTEGER,
TKN VARCHAR(10000))
AS
DECLARE VARIABLE I INTEGER;
DECLARE VARIABLE LEN INTEGER;
DECLARE VARIABLE FIRSTCHAR CHAR(1);
DECLARE VARIABLE S2 VARCHAR(10000);
begin
...
SUSPEND;
end^
then i build myself another sp (which also works fine) with this signature:
CREATE PROCEDURE GET_DICENTRIES_BY_ASDSKRPT (
ASDSKRPTINPUT VARCHAR(15))
RETURNS (
ID BIGINT)
AS
begin
...
suspend;
end^
now, what i'm trying to do is write another sp (get_dicentries_by_all_asdskrpts) that accepts a '.'-tokenized string as a parameter (e.g. 'bla.bli.blo.blu'; number of tokens NOT fixed at 4!) and returns the intersection of
GET_DICENTRIES_BY_ASDSKRPT('bla'), GET_DICENTRIES_BY_ASDSKRPT('bli'), GET_DICENTRIES_BY_ASDSKRPT('blo') AND GET_DICENTRIES_BY_ASDSKRPT('blu')
does any of you have an idea how to go about?
thanx,
martin
View 1 Replies
View Related
Jul 23, 2005
Could someone help me get the following SQL statement working?SELECTstandardgame.gamename,standardgame.rowteamname,standardgame.colteamname,standardgame.dollarvalue,standardgame.gameid,standardgame.cutoffdatetime,standardgame.gametype,standardgame.gameowner,(100-COUNT(purchasedsquares.gameid)) AS squaresremainingFROM standardgameLEFT OUTER JOINpurchasedsquares ON standardgame.gameid = purchasedsquares.gameidwhere gametype='$gametype' and dollarvalue = '$dollarvalue' andgameowner = 'GROUP BY standardgame.gameidorder byCASE squaresremaining WHEN 0 THEN 1 ELSE 0 END ASC,squaresremaining ASCThe problem is... MySQL doesn't seem to want to let me usesquaresremaining in that case statement since it's not an officialcolumn name. Any idea how I can reference squaresremaining in the casestatement?
View 2 Replies
View Related
Mar 13, 2007
I have a smalldatetime field in SQL.
For the query of my report, I need any transaction that is like 09/2006 (matching the month and year).
So I wrote something like this:
AND (DATE LIKE '%2006%')
That correctly returns all of the 2006 transactions.
Now why won't this work:
AND (DATE LIKE '%2006-09%')
Or how about this:
AND (DATE LIKE '%09%2006%')
What is the correct syntax??
View 3 Replies
View Related
Nov 2, 2007
am an ASP.net developer and i've stucked in a C# windows application ... and i am the linking part ... between the Database and my application ... in ASP i have a wizard that handles getting the data from the controls ... but is it the same in C# windows application ? am using VS2005 TeamSystem... and widows Vista(framework 3.0) .... and this query is getting executed and return 1 ... and the intellecence is telling me to insert 4 strings
int rowseffected = loginNamesTableAdapter.InsertQuery(textBox1.Text.ToString(), textBox2.Text.ToString(), textBox3.Text.ToString(), textBox4.Text.ToString());
MessageBox.Show(rowseffected.ToString());
i don't know how to link the parameters with the controls ... please show me how ... thx... please help with images ... as i previously mentioned... this is a new experment in C# thx.
__________________
Ahmed Reda
View 1 Replies
View Related
Jul 7, 2006
Hello,
I am trying to create a table if one with the same name does not exists. My code is:
Dim connectionString As String = "Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|PensionDistrict4.mdf;Integrated Security=True;User Instance=True"
Dim sqlConnection As SqlConnection = New SqlConnection(connectionString)
Dim newTable As String = "CREATE TABLE [" + titleString + "Comments" + "] (ID int NOT NULL PRIMARY KEY IDENTITY, Title varchar(100) NOT NULL, Name varchar(100) NOT NULL, Comment varchar(MAX) NOT NULL, Date datetime NOT NULL)"
sqlConnection.Open()
Dim sqlExists As String = "IF EXISTS (SELECT * FROM PensionDistrict4 WHERE name = '" + titleString + "Comments" + "')"
Dim sqlCommand As New SqlCommand(newTable, sqlConnection)
If sqlExists = True Then
sqlCommand.Cancel()
Else
sqlCommand.ExecuteNonQuery()
sqlConnection.Close()
End If
I keep getting a "Input String was incorrect format" for sqlExists? I am new to Transact-SQL statements, any help would be appreciated.
Thanks Matt
View 1 Replies
View Related
May 27, 2007
ok i have 2 tables---one table is name CourseInformation with a field named Instructor and the data in there looks like this 'John Doe'.
My other table Instructors has 3 fields InstructorName, LastName, FirstName.
I am grabbing the Instructor field from CourseInformation and breaking up the names and inserting them into my instructors table as follows..
Insert into Instructors(InstructorName, LastName, FirstName)
(Select Distinct
ltrim(SUBSTRING(Instructor,CHARINDEX(' ',Instructor)+1,len(Instructor)))+', '+
SUBSTRING(Instructor,1,CHARINDEX(' ',Instructor)-1),
ltrim(SUBSTRING(Instructor,CHARINDEX(' ',Instructor)+1,len(Instructor))) as LName,
SUBSTRING(Instructor,1,CHARINDEX(' ',Instructor)-1) as FNamefrom CourseInformation
where NOT EXISTS(Select * from instructors where LastName = LName and FirstName = FName)
AND Instructor is not null)
Only problem is, I cant get the where not exists clause to work right(of course that wont work what i have cuz the LName and FName columns dont exist, i just did that for demo purposes). I dont want duplicate instructors in there..how can i accomplish this..is there a better way to rewrite my query? Any help is appreciated.
View 3 Replies
View Related
Feb 7, 2008
HI All,Which is best among the two 1) NOT IN or 2) NOT EXISTS .If the query is Select col1 from tab1 where col2 NOT IN (Select col 3 from tab2 where cl3=0) OR Select col1 from tab1 where col2 NOT EXISTS (Select col 3 from tab2 where cl3=0)
View 2 Replies
View Related
Oct 12, 2001
Hi,
I have a question on the if not exists. Can you do something like this? If request not exists in table one then insert values into table two?
Thank you in advance,
Anne
View 3 Replies
View Related
Jul 15, 2004
Hi,
Is there any way to check whether a column is there in the table, if it is there i need to drop it through script.
i'm looking for the script, something like this..
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_Tbl_Product_Tbl_Products]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
ALTER TABLE [dbo].[Tbl_Product] DROP CONSTRAINT FK_Tbl_Product_Tbl_Products
GO
In the same way i need to check for a column and drop it through script.
Any help would be greatly appreciated.
Thanks in advance.
View 2 Replies
View Related
Jun 15, 2007
hi guys! is there anyway to retrieve the row from the result of EXISTS function aside from using the code below?
if EXISTS (select * from rcps_useraccount where User_login = 'daimous')
BEGIN
select * from rcps_useraccount where User_login = 'daimous'
END
View 3 Replies
View Related
May 16, 2008
Im having a problem with the following can anyone spot how i can fix it? I dont think it likes the begin statement but without it, it has a declare issue.
IF EXISTS (SELECT 1
FROM snapevent.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME='FastEp_Snap_OD_Acc' + preports.dbo.f_filedate(getdate())
begin
declare @CMD nvarchar(300)
Set @CMD = 'drop table Snap_OD_Acc_' + preports.dbo.f_filedate(getdate())
--print @CMD
exec (@CMD)
end
View 1 Replies
View Related
Jun 20, 2008
Hi
Please help me
I have to create a SP.
The secenario is that,
A application calls the SP with a parameter(login), and a string of datas ( Acctid level1 level2; Acctid level1 level2; .......)
UserID AcctID Level1 level2
test testee N Y
the SP have to get the first string of data and check if the Acctid exists or not. If yes then update else insert.Then get then the second string of data and check if the Acctid exists or not. If yes then update else insert.
After checking all the strings ,
it have to check if any Acctids other than acctid mentioned in the string exists in the table for that login, then delete those rows
View 1 Replies
View Related
Feb 18, 2006
I'm trying to perform an insert query on a table, but I also want to check to see if the record exists already in the table. It should be fairly simple, but I'm having a time of it. Should be something like:
select * from users u
inner join miamiherald m
on u.emailaddress = m.advertiseremail
where not u.emailaddress not exists <<< (???)
If it does exist, I then want to retrieve two columns from it. HELP!!
View 1 Replies
View Related
May 28, 2007
Hi,
The following works in SQL 2005 but NOT SQL 2005 Compact Edition:
IF EXISTS (SELECT ID FROM Court2 WHERE BookingDate = '2007-05-28')
UPDATE Court2 SET T1100 = 52 WHERE (BookingDate = '2007-05-28')
ELSE
INSERT INTO Court2 (BookingDate,T1100) VALUES ('2007-05-28',52)
In CE I get the following error:
There was an error parsing the query. [ Token line number = 1,Token line offset = 1,Token in error = IF ]
I can't find where the problem is - can someone help.
Thanks,
View 5 Replies
View Related
Dec 6, 2007
Dear all,
i am trying to improve the performance of stored procedures and functions in that in key word is there i have to replace with exists.which one will give better performance.
Thanks&Regards,
Msrs
View 2 Replies
View Related
Dec 6, 2007
Dear all,
i'm trying to replace in with exists...
i've changed the query but still i'm getting error.
please let me know where i'm missing
DELETE FROM table25 WHERE Col6='SET' AND Col1 IN (SELECT s.Col1 FROM Table24 s
WHERE Col2='some_data1' AND Col3='some_data2' AND Col4='somedata3')
DELETE FROM table25 r WHERE r.Col6='SET' AND exists (SELECT s.Col1 FROM Table24 s
WHERE r.col1=s.col2 and Col2='some_data1' AND Col3='some_data2' AND Col4='somedata3')
thank you very much
Vinod
Even you learn 1%, Learn it with 100% confidence.
View 9 Replies
View Related
Jan 15, 2008
I'm trying to search my table for a url, and if it in the table, increment the number of hits of the url. Here's my code:
tblLinks
-----------------------
URL | NumOfHits
-----------------------
ALTER PROCEDURE sproc_UpdateLink
(
@url varchar
)
AS
IF EXISTS(SELECT LinkURL
FROM tblLinks
WHERE @url = LinkURL)
BEGIN
UPDATE tblLinks
SET NumOfHits = NumOfHits + 1
WHERE @url = LinkURL
END
RETURN
I've also tried:
ALTER PROCEDURE sproc_UpdateLink
(
@url varchar
)
AS
IF (SELECT LinkURL
FROM tblLinks
WHERE @url = LinkURL) IS NOT NULL
BEGIN
UPDATE tblLinks
SET NumOfHits = NumOfHits + 1
WHERE @url = LinkURL
END
RETURN
but that didn't work either.
View 7 Replies
View Related
Mar 20, 2008
There's an error in this SQL statement somewhere, but I can't seem to find it. Here's what I'm trying to do:
I have a list of states, and each state is assigned an ID
For each state, I have some data
Given a state name, find the state's ID
If the state ID exists, output the data for that state
If the state ID is not in the database, output the data for all states
Here's my tables:
--------------------------
States
--------------------------
ID | Name
--------------------------
--------------------------
Data
--------------------------
StateID | StateData
--------------------------
Here's my SQL:
ALTER PROCEDURE sproc_GetStateData
(
@State varchar
)
AS
DECLARE @StateID int
IF EXISTS(SELECT @StateID = ID FROM States WHERE Name = @State)
BEGIN
SELECT D.StateData
FROM Data AS D INNER JOIN States AS S
ON D.StateID = S.ID
WHERE (D.StateID = @StateID)
END
ELSE
SELECT D.StateData
FROM Data AS D INNER JOIN States AS S
ON D.StateID = S.ID
RETURN
View 6 Replies
View Related
Jul 23, 2005
Hi,I need some help doing a simple query. Here is what I haveSELECT Category_Id, Category_nameFROM AG_Category WHERE Auth_Logic_Id = 244And Category_ID(I want category_id to not have a '.' in it. Basically returningeverything above but checking also the category_id so it doesn't returnone where category_id have a . in it)Thanks:D
View 1 Replies
View Related
Jul 23, 2005
I need to insert records into the table parSalesDetailModifier fromOLDparSalesDetailModifier where (1) those records DO NOT exit inparSalesDetailModifier and (2) those records have a parent record inparSalesDetail.When I run the below query I get the error message that I am violatingthe Primary Key Constraint for parSalesDetailModifier. In other words,it's trying to insert a record that does exist.Also posted below are create and insert startements for thte tables.If someone would be kind enough to show me what I am doing wrong, I'dreally appreciate it.Thanks,Jennifer-------------------------------- STORED PROCEDURE-------------------------------CREATE Proc LoadModifier2@S datetime,@E datetimeASINSERT INTO ParSalesDetailModifier(parSalesDetailModifierID,parSalesHdrID,parSalesDetailID,ModifierType,POSModifier,Condiment,CondimentPrice,UnitNumber,BusinessDay)SELECTOLD.parSalesDetailModifierID,OLD.parSalesHdrID,OLD.parSalesDetailID,OLD.ModifierType,OLD.POSModifier,OLD.Condiment,OLD.CondimentPrice,OLD.UnitNumber,OLD.BusinessDayFROM OldParSalesDetailModifier OLDWHEREEXISTS( SELECT DET.parSalesHdrID,DET.parSalesDetailID,DET.UnitNumber,DET.BusinessDayFROM ParSalesDetail DETWHERE OLD.parSalesHdrID = DET.parSalesHdrIDANDOLD.parSalesDetailID = DET.parSalesDetailIDANDOLD.UnitNumber = DET.UnitNumberANDOLD.BusinessDay = DET.BusinessDay)ANDNOT EXISTS( SELECT NEW.parSalesHdrID,NEW.parSalesDetailID,NEW.parSalesDetailModifierID,NEW.UnitNumber,NEW.BusinessDayFROM ParSalesDetailModifier NEWWHERE OLD.parSalesHdrID = NEW.parSalesHdrIDANDOLD.parSalesDetailID = NEW.parSalesDetailIDANDOLD.parSalesDetailModifierID = NEW.parSalesDetailModifierIDANDOLD.UnitNumber = NEW.UnitNumberANDOLD.BusinessDay = NEW.BusinessDay)AND OLD.BusinessDay between @S and @E-------------------------------- END STORED PROCEDURE--------------------------------------------------------------- CREATE TABLES-------------------------------CREATE TABLE [parSalesDetailModifier] ([ParSalesDetailModifierID] [int] NOT NULL ,[parSalesHdrID] [int] NOT NULL ,[parSalesDetailID] [int] NOT NULL ,[ModifierTYPE] [int] NULL ,[POSModifier] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,[Condiment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[CondimentPrice] [money] NOT NULL ,[UnitNumber] [int] NOT NULL ,[BusinessDay] [datetime] NOT NULL ,CONSTRAINT [PK_parSalesDetailModifier] PRIMARY KEY CLUSTERED([BusinessDay],[UnitNumber],[parSalesHdrID],[parSalesDetailID],[ParSalesDetailModifierID]) WITH FILLFACTOR = 70 ON [PRIMARY] ,CONSTRAINT [FK_parSalesDetailModifier_parSalesDetail] FOREIGN KEY([BusinessDay],[UnitNumber],[parSalesHdrID],[parSalesDetailID]) REFERENCES [parSalesDetail] ([BusinessDay],[UnitNumber],[parSalesHdrID],[parSalesDetailID])) ON [PRIMARY]GOCREATE TABLE [OLDparSalesDetailModifier] ([ParSalesDetailModifierID] [int] NOT NULL ,[parSalesHdrID] [int] NOT NULL ,[parSalesDetailID] [int] NOT NULL ,[ModifierTYPE] [int] NULL ,[POSModifier] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,[Condiment] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[CondimentPrice] [money] NOT NULL ,[UnitNumber] [int] NOT NULL ,[BusinessDay] [datetime] NULL) ON [PRIMARY]GOCREATE TABLE [parSalesDetail] ([parSalesHdrID] [int] NOT NULL ,[parSalesDetailID] [int] NOT NULL ,[Before] [int] NOT NULL ,[Quantity] [int] NOT NULL ,[After] [int] NOT NULL ,[Promo] [money] NOT NULL ,[PromoBefore] [money] NOT NULL ,[ItemPrice] [money] NOT NULL ,[PromoAfter] [money] NOT NULL ,[POSItem] [varchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[UnitNumber] [int] NOT NULL ,[Depleted] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,[AmountTenderTime] [datetime] NULL ,[BusinessDay] [datetime] NOT NULL ,CONSTRAINT [PK_parSalesDetail] PRIMARY KEY CLUSTERED([BusinessDay],[UnitNumber],[parSalesHdrID],[parSalesDetailID]) WITH FILLFACTOR = 70 ON [PRIMARY] ,CONSTRAINT [FK_parSalesDetail_parSalesHdr] FOREIGN KEY([BusinessDay],[UnitNumber],[parSalesHdrID]) REFERENCES [parSalesHdr] ([BusinessDay],[UnitNumber],[parSalesHdrID])) ON [PRIMARY]GO-------------------------------- END CREATE TABLES--------------------------------------------------------------- INSERT INTO TABLES-------------------------------insert into parSalesDetailmodifier values (1,2298561,10917332,2,'ADDG-ON','ADD G-ON',.0000,2,'2003-12-01')insert into oldparSalesDetailmodifier values (1,2298561,10917332,2,'ADDG-ON','ADD G-ON',.0000,2,'2003-12-01')insert into oldparSalesDetailmodifier values (2,2298561,10917332,2,'SUBMAYO','SUB MAYO',.0000,2,'2003-12-01')insert into oldparSalesDetailmodifier values(3,2298561,10917332,2,'TBBS','TBBS',.0000,2,'2003-12-01')insert into oldparSalesDetailmodifier values (1,2298561,10917340,2,'SUBMAYO','SUB MAYO',.0000,2,'2003-12-01')insert into oldparSalesDetailmodifier values (2,2298561,10917340,2,'NOONIN','NO ONIN',.0000,2,'2003-12-01')insert into oldparSalesDetailmodifier values(3,2298561,10917340,2,'TBBS','TBBS',.0000,2,'2003-12-01')insert into oldparSalesDetailmodifier values(4,2298561,10917340,2,'WELL','WELL',.0000,2,'2003-12-01')insert into oldparSalesDetailmodifier values (1,2298561,10917341,2,'ADDG-ON','ADD G-ON',.0000,2,'2003-12-01')insert into oldparSalesDetailmodifier values (2,2298561,10917341,2,'SUBMAYO','SUB MAYO',.0000,2,'2003-12-01')insert into oldparSalesDetailmodifier values(3,2298561,10917341,2,'TBBS','TBBS',.0000,2,'2003-12-01')insert into parSalesDetailvalues(2298561,10917332,0,1,0,.0000,.0000,3.4900,. 0000,'DM',2,'N','2003-12-0110:00:02.000','2003-12-01')insert into parSalesDetailvalues(2298561,10917340,0,1,0,.0000,.0000,.2500,.0 000,'JALA',2,'N','2003-12-0110:00:02.000','2003-12-01')insert into parSalesDetailvalues(2298561,10917341,0,1,0,.0000,.0000,1.3400,.0000,'MD-DP',2,'N','2003-12-0110:00:02.000','2003-12-01')insert into parSalesDetailvalues(2298561,10928910,0,1,0,.0000,.0000,.9900,.0000,'2PIE99',2,'N','2003-12-0110:00:02.000','2003-12-01')insert into parSalesDetailvalues(2298561,10928911,0,1,0,.0000,.0000,.5900,.0000,'DECAF',2,'N','2003-12-0110:09:44.000','2003-12-01')insert into parSalesDetailvalues(2298561,10928912,0,1,0,.0000,.0000,1.6900,.0000,'BOB-BAC',2,'N','2003-12-0110:09:44.000','2003-12-01')insert into parSalesDetailvalues(2298561,10929376,0,1,0,.0000,.0000,.5900,.0000,'COFFEE',2,'N','2003-12-0110:00:44.000','2003-12-01')-------------------------------- END INSERT INTO TABLES-------------------------------
View 7 Replies
View Related
Oct 31, 2007
Hi,
I'm having problems with this T-SQL:
Sorry if this is obvious, I'm very new to this...
Just trying to return the ID if the row exists and if not just return 0.
What would I need to turn this into a stored procedure too?
Code Block
declare @Return int
if exists(select id from Computer where Computer_name = 'MYCOMPUTER')
begin
select @Return = id
PRINT @Return
end
else
begin
select @Return = 0
PRINT @Return
end
I'm getting this error....
Msg 207, Level 16, State 1, Line 5Invalid column name 'id'.Msg 207, Level 16, State 1, Line 10Invalid column name 'id'.
View 5 Replies
View Related
Mar 10, 2008
I'm running into a problem on my SQL2000 server. I thought all 3 of the following queries SHOULD return the same results, but the query using the NOT IN does not return any records where the other 2 queries DO.
Is my understanding of NOT IN wrong, or is there something corrupt in my DB?
SELECT *
FROM [person]
WHERE personid NOT IN (SELECT personid FROM [personOrganization])
SELECT *
FROM [person]
LEFT OUTER JOIN [personOrganization]
ON [Person].[personId] = [personOrganization].[personId]
WHERE [personOrganization].personid IS NULL
SELECT *
FROM person
WHERE NOT EXISTS(SELECT 1 FROM [personOrganization] WHERE [personOrganization].personid=person.personid)
View 11 Replies
View Related
Mar 25, 2008
Hi all,
I'm trying to run "alter table" to add a new column to the tables but the problem is some of the tables have the column and some don't.
Is there a way to use if not exists to alter the tables with no column only??
thanks,
View 7 Replies
View Related
Aug 30, 2006
Well, finally I lost one day to find a solution for a simple problem. I
wanted to derive two tables... that seemed to be simple... but it isn't.
My last question for today:
Why does my sql query return the error: Only one expression can be specified in the select list when the subquery is not introduced with EXISTS
The Query:
SELECT
Configurations.AlarmId, Configurations.Mode, Configurations.Activated,
Configurations.Empty, Configurations.UserName, Configurations.datetime,
(SELECT ConfigurationId, Setpoint1, Alarm
FROM
dbo.ExtendedValues(Configurations.ConfigurationId) AS ExtendedValues)
AS Expr1
FROM Configurations INNER JOIN
Controllers ON Configurations.ConfigurationId =
Controllers.ActiveConfig INNER JOIN
Tanques ON Controllers.ControllerId = Tanques.ControllerId
WHERE (Tanques.TanqueId = 1)
Where do I have to enter EXISTS?
Thanks for every hint!!
P.D.: The ExtendedValues Function:
CREATE FUNCTION dbo.ExtendedValues
(
@ConfigurationId int = -1
)
RETURNS TABLE
AS
RETURN SELECT *
FROM ConfigurationsTanques
WHERE ConfigurationsTanques.ConfigurationId = @ConfigurationId
View 1 Replies
View Related
Jul 24, 2006
Using Vs2005 sqlServer 2005 When i try to connect i get this error: An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) Connection string: <connectionStrings> <add name="pubsConnectionString1" connectionString="Data Source=.;Initial Catalog=pubs;User=mk;pw=x" providerName="System.Data.SqlClient" /> </connectionStrings> Calling code : try { using (SqlConnection cn = new SqlConnection(WebConfigurationManager.ConnectionStrings[0].ConnectionString)) { cn.Open(); } } catch (Exception ex) { Response.Write(ex.Message); }
View 1 Replies
View Related
Mar 2, 2007
I have a table adapter query with a like clause that I can't get to work. The field is "Type", so I have "LIKE '%@Type%'". When I click the Execute Query button to test, not only does nothing get returned, I don't get the chance to enter the parameter. If I change LIKE '%@Type%' to say, LIKE '%book%', the appropriate records are returned. I actually need to check two parameters. If I ad the second parameter, the where clause becomes(Type LIKE '%@Type%') AND (SendState = @SendState)When I test the query, a screen pops up to let me enter the state, but not the Type. I can't see anything wrong with the query, but something must be. Diane
View 4 Replies
View Related
Jun 6, 2007
I am having a most frustrating time getting this working. I have two machines, one named 'REMOTE' and it contains my SQL Server (2005 developer edition). Then I have my main PC, named 'DOUGAL' The server instance on the REMOTE computer is called 'SQLSERVER' and there is only one instance. The server is showing as running etc and I can log in locally on the REMOTE computer easily via the Microsoft SQL Server Management Studio etc. I have two logins that are working fine, sa and a login called 'db_user'.Now I am trying to connect in the server explorer in visual studio. When I try and connection i get the following error; An Error has occured while establishing a connection to the server. When connectiong to SQL Server 2005 this failure may be caused by the fact that under the default settings SQL server does not allow remote connections. (provder: Named Pipes Provider, error: 40 - Count not open connection to SQL Server). I have tried connection to 'REMOTE/SQLSERVER' 'REMOTE' and with its IP address to - without any luck. So, to fix this problem I have checked that remote connections are allowed (and restarted the system). I have also checked that named pipes and tcp/ip connections are enabled. I have searched around with the aid of my best friend, Google. However, I've only found suggestions that involve trying the fixes I already tried.
View 4 Replies
View Related
Nov 6, 2007
Ok, what I am tryin to do is quite simple i do believe. Basically I have an aspx page with a textbox, a button and a datagrid linked to my sql db. What I am wanting is for a user to enter in their Social Security Number in the text box and click the button. If the SSN matches a record in the DB then it binds to the datagrid and shows it, IF no match is found then it displays a link to click on to continue onto the next page. This is to stop duplicate entries. I can get one to work by itself but not both of them at the same time. Here is my code.<%@ Page Language="VB" %><%@ Import Namespace="System.Data" %><%@ Import Namespace="System.Data.SqlClient" %><script language="VB" runat="server"> Sub btnSearch_OnClick(sender as Object, e as EventArgs) Dim objConnection As SqlConnection Dim objCommand As SqlCommand Dim objAdapter As SqlDataAdapter Dim objDataSet As DataSet Dim strSearch As String Dim strSQLQuery As String ' Get Search strSearch = txtSearch.Text ' If there's nothing to search for then don't search ' o/w build our SQL Query and execute it. If Len(Trim(strSearch)) > 0 Then OK, Here is my first IF, this works. ' Set up our connection. objConnection = New SqlConnection("Data Source=BRADBLACKBUR-PCMSSMLBIZ;" _ & "Initial Catalog=Victorypoint;Integrated Security=True;") ' Set up our SQL query text. strSQLQuery = "SELECT FirstName, LastName, SSN " _ & "FROM Applicants " _ & "WHERE SSN LIKE '%" & Replace(strSearch, "'", "''") & "%' " _ & "ORDER BY SSN;" ' Create new command object passing it our SQL query ' and telling it which connection to use. objCommand = New SqlCommand(strSQLQuery, objConnection) ' Get a DataSet to bind the DataGrid to objAdapter = New SqlDataAdapter(objCommand) objDataSet = New DataSet() objAdapter.Fill(objDataSet) If objDataSet.Tables.Count < 1 Then Right here is where I am having the problem, I need to count the Rows not the Tables, but I dont know what code i should use here. Button1.Visible = True Else ' DataBind DG to DS dgSearch.DataSource = objDataSet dgSearch.DataBind() objConnection.Close() End If End If End Sub
View 2 Replies
View Related
May 5, 2008
I've tried to post this somewhere else, but I haven't gotten it figured out yet:
I'm passing variables through a URL, and the page that accepts the variables has a where clause like this:"WHERE (name1 LIKE @name1 + '%') and (property_add like @property_add + '%') and (ctlmap = @ctlmap )"On the search page where the variables are entered, the user may not know all the information that goes into each input field. (If the user just knew the name, they would search by name. If the user just knew the address, they would search by address...etc.) Everything works great before I add the ctlmap variable. When the ctlmap variable is added, no search results will turn up unless there is an entry made to the ctlmap field. I know it has to have something to do with the ctlmap being set to equals rather than like, but I can't find a way to make the search work with a null value for ctlmap. Thanks, everyone. Additional Info: <SelectParameters> <asp:QueryStringParameter ConvertEmptyStringToNull="False" Name="name1" QueryStringField="name" Type="String" /> <asp:QueryStringParameter ConvertEmptyStringToNull="False" Name="property_add" QueryStringField="address" /> <asp:QueryStringParameter ConvertEmptyStringToNull="False" Name="ctlmap" QueryStringField="ctlmap" /> </SelectParameters>
Here's another type of where clause that I tried but had no luck with:
WHERE (name1 LIKE @name1 + '%') and (property_add like @property_add + '%') and (@ctlmap IS NULL or @ctlmap = ctlmap)
This is how I would try to do it in php/mysql, but I don't know how to make it work in asp.net/sql:
if ($ctlmap != "") { $whereClause = $whereClause." and ctlmp = '".strtoupper($ctlmap)."' "; } if ($whereClause != "") { $whereClause = " where ".$whereClause; }Here's the MYSQL counterpart:$sqlString = "Select distinct district, map, bill_group, ctlmap, bill_parcel, propertyid, special, property_add, name1 from MUR_bill_master".$whereClause";
Can anyone help?
View 11 Replies
View Related
Jun 9, 2004
Greetings,
I am having difficulty connecting to a SQL DB in my ASP page. Each time I run my application I receive the following error, "Login failed for user 'CX259ASPNET'". This is obviously something to do with permissions. I am all out of ideas but I will list the things I have already attempted to see if I either missed something or somebody can add to what I have already done.
1. In SQL Server I right-clicked the db -> properties -> security tab -> selected the option button to "SQL Server and Windows" instead of "Windows Only".
2. I installed SP3 and changed the sa password.
3. I created a new user under my db using the ASPNET account listed. I then changed the permissions to allow selecting, update, insert and delete access.
4. I also created a new user under my db using the IUSR account listed. I changed the permissions to the same settings as above.
I did a search on google which provided with all of the information above, but I am still stuck and hoping that this is a common problem and will be easy to fix.
Below is the code which I am attempting to use.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
Dim strConnString As String = _
"Data Source=(local);" & _
"Initial Catalog=Names;" & _
"Integrated Security=SSPI;"
Dim objConn As New SqlConnection(strConnString)
Dim strSQL As String = "SELECT * FROM [Names]"
Dim objCmd As New SqlCommand(strSQL, objConn)
objConn.Open()
MyDataGrid.DataSource = objCmd.ExecuteReader
MyDataGrid.DataBind()
objConn.Close()
End If
End Sub
Regards,
Corey
View 11 Replies
View Related