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


ADVERTISEMENT

How To Update If Exists Else Insert In One SQL Statement

Jul 20, 2005

In MS Access I can do in one SQL statement a update if exists else ainsert.Assuming my source staging table is called - SOURCE and my targettable is called - DEST and both of them have the same structure asfollowsKeycolumns==========MaterialCustomerYearNonKeyColumns=============SalesIn Access I can do a update if the record exists else do a insert inone update SQL statement as follows:UPDATE DEST SET DEST.SALES = SOURCE.SALESfrom DEST RIGHT OUTER JOIN SOURCEON (DEST.MATERIAL = SOURCE.MATERIAL ANDDEST.CUSTOMER = SOURCE.CUSTOMER ANDDEST.YEAR = SOURCE.YEAR)This query will add a record in SOURCE into DEST if that record doesnot exist in DEST else it does a update. This query however does notwork on SQL 2000Am I missing something please share your views how I can do this inSQL 2000.ThanksKaren

View 6 Replies View Related

Return Primary Key On INSERT Statement

Jul 20, 2005

I am inserting a record into a table that automatically generatesunique ids (i.e. Primary Key). Is there anyway to return this id. As Iam using this on ASP.net page and I really need the ID to update thepage with the new details.I think on mysql there is something called LAST_INSERT_ID which doesthis.

View 10 Replies View Related

Insert Statement Which Uses A Return Value From An SP As An Insert Value

Jul 20, 2005

I'm quite stuck with this:I have an import table called ReferenceMatchingImport which containsdata that has been sucked from a data submission. The contents ofthis table have to be imported into another table ExternalReferencewhich has various foreign keys.This is simple but one of these keys says that the value inExternalReference.CompanyRef must be in the CompanyReference table.Of course if this is an initial import then it will not be so as partof my script I must insert a new row into CompanyReference andpopulate ExternalReference.CompanyRef with the identity column of thistable.I thought a good idea would be to use an SP which inserts a new rowand returns @@Identity as the value to insert. However this doesn'twork as far as I can tell. Is there a approved way to perform thissort of opperation? My code is below.Thanks.ALTER PROCEDURE SP00ReferenceMatchingImportAS/*Just some integrity checking going on here*/INSERT ExternalReference(ExternalSourceRef,AssetGroupRef,CompanyUnitRef,EntityTypeCode,CompanyRef, --this is the unknown ref which is returned by the spExternalReferenceTypeCode,ExternalReferenceCompanyReferenceMapTypeCode,StartDate,EndDate,LastUpdateBy,LastUpdateDate)SELECT rmi.ExternalDataSourcePropertyRef,rmi.AssetGroup,rmi.CompanyUnit,rmi.EntityType,SP01InsertIPDReference rmi.EntityType, --here I'm trying to run thesp so that I can use the return value as the insert value1,1,GETDATE(),GETDATE(),'RefMatch',GETDATE()FROM ReferenceMatchingImport rmiWHERE rmi.ExternalDataSourcePropertyRef NOT IN (SELECT ExternalSourceRefFROM ExternalReference)

View 3 Replies View Related

Can INSERT Statement Also Return All Columns Inserted As Result Set

Jun 2, 2014

Can an INSERT statement also return all columns inserted as a result set? If so what clause of the INSERT statement does this?

View 3 Replies View Related

SQL 2012 :: Can INSERT Statement Also Return All Columns Inserted As Result Set

Jun 2, 2014

Can an INSERT statement also return all columns inserted as a result set? If so what clause of the INSERT statement does this?

View 2 Replies View Related

Transact SQL :: INSERT Array Of Integer Into Table - Wrong Return Value Of Statement In ODBC

Sep 30, 2015

I would like to INSERT an array of integer into a table in MSSQL Server, then count the number of rows in the table with c++ using ODBC. Here you find my code to do this task:

#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include<tchar.h>
#include <sql.h>
#include <sqlext.h>
#include<sqltypes.h>

[Code] ....

In my code, I would like to Insert the array and then count the number of rows:

SQLTCHAR Statement[] = _T("INSERT INTO information1(Wert1,Wert2) VALUES(?,?) select count(*) as a from information1 ") ;

Problem : My expectation is, that first 9 rows are inserted into table then comes 9 as result to user (if the table is empty) but this code returns me 1 if first the table is empty. If the table is not empty, it returns 1+number of  existing rows in the table. If I take a look inside the table, the 9 rows are successfully inserted in it. Only the number of rows in the table is wrong.

Hint : If I monitor the database using SQL Profiler. It looks like this:

Why this statement doesn't work correctly?

View 7 Replies View Related

Attempt To Return Record Set In INSERT...EXEC Statement From ODBC Source(non MSSQL)

Jan 17, 2007

Greeting.

I use OdbcConnection inside clr procedure, for getting data. If I use simple EXEC dbo.clr_proc - all is OK. If I use INSERT...EXEC I recive error message: Distributed transaction enlistment failed.

I set MSDTC security options for No Authentification and Allow inbound and Allow outbound, but it's no use.

Have this problem solution? May be, I must use another method to get my data?



P.S. Linked Servers and OPENQUERY is not applicable. Sybase not describe columns in stored proc result set and one stored proc may return different result set by params.

P.S.S. Sorry for bad english.









View 1 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

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 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

'Return' Statement In A Function,Get,or Operator Must Return A Value....Question

Aug 28, 2007


I'm a Reporting Services New-Be.

I'm trying to create a report that's based on a SQL-2005 Stored Procedure.

I added the Report Designer, a Report dataset ( based on a shared datasource).

When I try to build the project in BIDS, I get an error. The error occurs three times, once for each parameter on the stored procedure.

I'll only reproduce one instance of the error for the sake of brevity.

[rsCompilerErrorInExpression] The Value expression for the query parameter 'UserID' contains an error : [BC30654] 'Return' statement in a Function, Get, or Operator must return a value.

I've searched on this error and it looks like it's a Visual Basic error :

http://msdn2.microsoft.com/en-us/library/8x403818(VS.80).aspx

My guess is that BIDS is creating some VB code behind the scenes for the report.

I can't find any other information that seems to fit this error.

The other reports in the BIDS project built successfully before I added this report, so it must be something specific to the report.

BTW, the Stored Procedure this report is based on a global temp table. The other reports do not use temp tables.

Can anyone help ?

Thanks,

View 5 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

SQL Server 2012 :: Create Dynamic Update Statement Based On Return Values In Select Statement

Jan 9, 2015

Ok I have a query "SELECT ColumnNames FROM tbl1" let's say the values returned are "age,sex,race".

Now I want to be able to create an "update" statement like "UPATE tbl2 SET Col2 = age + sex + race" dynamically and execute this UPDATE statement. So, if the next select statement returns "age, sex, race, gender" then the script should create "UPDATE tbl2 SET Col2 = age + sex + race + gender" and execute it.

View 4 Replies View Related

Using The IF EXISTS Conditional Statement

Apr 5, 2007

I'm trying to gather some user statistics based on 3 conditions. First I want to check if the referring querystring is already in the database. If not insert it into the db. Second, if the querystring is already in the database, then check if the ip-address of the user is already in the database. If it is, then check if the ip address was inserted today. If not, update the "refCountIn" field with +1. The problem lies in the third condition where we check if the ip-address was inserted today and if false, update the "refCountIn" field with +1 and if true, do nothing.Below is the code I have until now:  1 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
2
3 ' *** Declare the variables
4 Dim getStatCmd As String
5 Dim updStatCmd As String
6
7 Dim myRef As String = Request.QueryString("ref")
8 Dim myQueryString As String = Request.ServerVariables("QUERY_STRING").Replace("ref=", "")
9 Dim myRemoteAddr As String = Request.ServerVariables("REMOTE_ADDR")
10 Dim myHttpReferer As String = Request.ServerVariables("HTTP_REFERER")
11
12 Dim dtNow As Date = DateTime.Now
13 Dim dtToday As Date = DateTime.Today
14
15 ' *** Conditional INSERT command
16 getStatCmd = _
17 "IF EXISTS(SELECT 'True' FROM tblReferers WHERE robotName = '" & myQueryString & "' AND refIpAddress = '" & myRemoteAddr & "' AND refTime = '" & dtToday & "') " & _
18 "BEGIN " & _
19 "SELECT 'This clickin has already been recorded!'" & _
20 "END ELSE BEGIN " & _
21 "SELECT 'Clickin recorded' " & _
22 "INSERT INTO tblReferers(robotName, refIpAddress, refReferer, refTime) " & _
23 "VALUES(" & _
24 "'" + myQueryString + "'," & _
25 "'" + myRemoteAddr + "'," & _
26 "'" + myHttpReferer + "'," & _
27 "'" + dtToday + "')" & _
28 "END "
29
30
31 ' *** Conditional UPDATE command
32 updStatCmd = _
33 "IF EXISTS(SELECT 'True' FROM tblReferers WHERE robotName = '" & myQueryString & "' AND refIpAddress = '" & myRemoteAddr & "' AND refTime <> '" & dtToday & "') " & _
34 "UPDATE tblReferers " & _
35 "SET refCountIn = refCountIn + 1, refTime = '" & dtNow & "' " & _
36 "WHERE refIpAddress = '" & myRemoteAddr & "' AND robotName = '" & myRef & "'"
37
38 Dim insConnCmd As New SqlCommand(getStatCmd, New SqlConnection(connSD))
39 Dim updConnCmd As New SqlCommand(updStatCmd, New SqlConnection(connSD))
40
41 insConnCmd.Connection.Open()
42 insConnCmd.ExecuteNonQuery()
43 insConnCmd.Connection.Close()
44
45 updConnCmd.Connection.Open()
46 updConnCmd.ExecuteNonQuery()
47 updConnCmd.Connection.Close()
48
49 End Sub
Anyone with an idea on how to solve this one? I think I need to write a subquery for the third condition, but I don't have a clue on how to handle this.Thanks in advance for your help! 
 

View 2 Replies View Related

If Exists Statement Problem...

Jun 16, 2004

Can someone give me a hand with this?

Ok I have a table called allstocks, with a primary key of ticker, I also have a todaysstocks table with a primary key of ticker.

Todaysstock table updates the allstocks table with this statement,

insert into allstocks (exchange,transdate,ticker,[opened date],[closed date],[over/under]) select exchange,[todays date],ticker,[opened date], [closed date],[over/under] from todaysstocks

this works fine, unless the ticker already exists. How do I write the statement, that if the ticker already exists, then update the rest of the fields with the new info, or delete the row and recreate it?

ANy help would be appreciated. Thanks

View 4 Replies View Related

How To Set A Variable In An If Exists Statement

Feb 28, 2008



Hello,

I would like to set a variable within my if exists statement, however SQL is throwing and error stating:


Incorrect syntax near '='.

If I remove the if exists, the query runs fine. Is there a reason why this is not working the way I have it and what suggestions can I use to accomplish what I am trying to do, which is store the ID into the permissionID variable

Here is my code block:



Code Snippet

declare @permissionID int;

if exists(select @permissionID = Id from Permission

where [Description] = 'SettlementReport')






Thanks,
Flea#

View 3 Replies View Related

ALTER PROCEDURE Statement Within IF EXISTS

May 28, 2002

Hello.

I'm trying to create a batch sql script which first alters some existing tables via the ALTER TABLE command, I then want to alter some existing stored procedures via the ALTER PROCEDURE command within the same batch. I have found that I can encompas the alter table scripts within a conditional IF EXISTS (Begin/End) but not the alter procesdure scripts. I have looked in reference material and have found nothing to suggest this type of operation is not possible. Is this possible? Is this a know bug fixed by a service pack?

Thanks in advance for any replies.
David.

View 3 Replies View Related

IF EXISTS Statement In My Perl Program

Aug 23, 2004

I am having trouble finishing my query.

This is what I have:

IF EXISTS(Select ApplicationID from Application Where Application = '&_')
Insert Into PCApp(ApplicationID, SystemNetName)
Values( , $HoH->{Host}{SystemNetName})

I am not sure what to put in the blank within the Values parenthesis. I need to obtain the ApplicationID that is checked in the IF EXISTS section. But I cannot put a select statement into the Values() section.

Any suggestions would be appreciated.

Thanks,
Laura

View 13 Replies View Related

Stored Procedure Exists Statement

Feb 26, 2008

When I created an SP in Enterprise Manager, I didn't manually type in the existence check at the inception, a la "if exists (select * from sysobjects...)". I just started with the CREATE PROC AS statement.

I noticed that if I generate a SQL script for the SP, SQL2000 automatically generates the existence check statement.

My question is, can I assume that when the SP is actually executed, SQL2000 does the exists check on its own? I EXEC'd the proc in Query Analyzer with no errors.

I just want to make sure that I don't need to enter the exists statement if it's already being done behind the scenes.

View 3 Replies View Related

Insert If Not Exists

Mar 8, 2005

I have two tables that I have to compare:


Code:


Table:PR
WBS1 WBS2 WBS3
123-456 1000 01
123-456 1000 02
123-456 2000 02
567-890 2000 01
567-890 2000 02

Table:PR_Template
WBS2 WBS3
1000 00
1000 01
1000 02
2000 00
2000 01
2000 02

After Insert I should have:

wbs1 wbs2 wbs3
123-456 1000 00
123-456 1000 01
123-456 1000 02
123-456 2000 00
123-456 2000 01
123-456 2000 02
567-890 1000 00
567-890 1000 01
567-890 1000 02
567-890 2000 00
567-890 2000 01
567-890 2000 02





Basically, I need to insert the wbs2 and wbs3 where it does not exist in each wbs1.

What I have now will find the values that need to be inserted for a particular project but I don't know how to go through each project and perform the insert:

Select * from PR_template Where Not Exists
(Select Wbs1, Wbs2, Wbs3 from PR where PR.WBS2 = PR_Template.WBS2
And PR.WBS3 = PR_Template.Wbs3 and pr.wbs1 = '123-456')
Order by wbs2, wbs3 asc

Thank You

View 6 Replies View Related

Msg 156 On Insert Where Not Exists

Sep 28, 2007

I'm getting the following error on this query:

Insert into ILS_CustList values ('05-888', '05-888 - NV') where not exists (select jobid from ILS_CustList where jobid = '05-888')


Msg 156, Level 15, State 1, Line 1

Incorrect syntax near the keyword 'where'.


What's the problem?
Thanks!

View 5 Replies View Related

Trying To Select Info With If Exists Statement With No Avail

Jan 6, 2004

Im trying to select rows on the following criteria

My app has a user that can have x jobs, each job has related entries which are marked has unread or read. I need to return any jobs that contain any unread entries also I need to return other jobs that have no entries marked as read.

I am able to return the following:


Comment UnReadMy Job 164
Comment UnReadFor Cam 166

Comment ReadThe Job 157
Comment ReadThird 159
Comment ReadMy Job 164
On Site Visit ReadMy newest job for log test 167

but as you can see jobid 164 appears in both groups and I need it to be one or the other

I tried using the if exists statement and was only able to return one group either unread or read, not both. I've tried everything but I'm new and I figure that theres got to be a more elegant way. Heres my sql:


CREATE PROCEDURE spGetJobsByUnreadAndReadByUserID
@UserID INT
AS


BEGIN
IF EXISTS(SELECT DISTINCT Master_Jobs.JobID, Profiles.ProfileDescriptor, Backup_UserNotes.BackUp_Read, Master_Jobs.Job_Title, Master_Jobs.Contact,
Master_Jobs.Due_Date, Master_Jobs.Due_Time, Master_Jobs.Next_Action, Master_Jobs.By_Who

FROM Master_Jobs INNER JOIN
Note ON Master_Jobs.JobID = Note.FK_JobID INNER JOIN
Backup_UserNotes ON Note.NoteID = Backup_UserNotes.BackUp_NoteID INNER JOIN
User_Notes ON Note.NoteID = User_Notes.FK_UN_NoteID INNER JOIN
Job_Assignments ON Master_Jobs.JobID = Job_Assignments.FK_Master_JobID INNER JOIN
Profiles ON Master_Jobs.FK_ProfileID = Profiles.ProfileID INNER JOIN
Users ON Backup_UserNotes.BackUp_UserID = Users.UserID AND User_Notes.FK_UN_UserID = Users.UserID AND
Job_Assignments.UserID = Users.UserID

WHERE Users.UserID = @UserID AND-- Note.FK_UserID = User_Notes.FK_UN_UserID AND
BackUp_Read = 'UnRead')


BEGIN
SELECT DISTINCT Master_Jobs.JobID, Profiles.ProfileDescriptor, Backup_UserNotes.BackUp_Read, Master_Jobs.Job_Title, Master_Jobs.Contact,
Master_Jobs.Due_Date, Master_Jobs.Due_Time, Master_Jobs.Next_Action, Master_Jobs.By_Who

FROM Master_Jobs INNER JOIN
Note ON Master_Jobs.JobID = Note.FK_JobID INNER JOIN
Backup_UserNotes ON Note.NoteID = Backup_UserNotes.BackUp_NoteID INNER JOIN
User_Notes ON Note.NoteID = User_Notes.FK_UN_NoteID INNER JOIN
Job_Assignments ON Master_Jobs.JobID = Job_Assignments.FK_Master_JobID INNER JOIN
Profiles ON Master_Jobs.FK_ProfileID = Profiles.ProfileID INNER JOIN
Users ON Backup_UserNotes.BackUp_UserID = Users.UserID AND User_Notes.FK_UN_UserID = Users.UserID AND
Job_Assignments.UserID = Users.UserID

WHERE Users.UserID = @UserID AND-- Note.FK_UserID = User_Notes.FK_UN_UserID AND
BackUp_Read = 'UnRead'

ORDER BY BackUp_Read ASC
END

ELSE

BEGIN


SELECT DISTINCT Master_Jobs.JobID, Profiles.ProfileDescriptor, Backup_UserNotes.BackUp_Read, Master_Jobs.Job_Title, Master_Jobs.Contact,
Master_Jobs.Due_Date, Master_Jobs.Due_Time, Master_Jobs.Next_Action, Master_Jobs.By_Who

FROM Master_Jobs INNER JOIN
Note ON Master_Jobs.JobID = Note.FK_JobID INNER JOIN
Backup_UserNotes ON Note.NoteID = Backup_UserNotes.BackUp_NoteID INNER JOIN
User_Notes ON Note.NoteID = User_Notes.FK_UN_NoteID INNER JOIN
Job_Assignments ON Master_Jobs.JobID = Job_Assignments.FK_Master_JobID INNER JOIN
Profiles ON Master_Jobs.FK_ProfileID = Profiles.ProfileID INNER JOIN
Users ON Backup_UserNotes.BackUp_UserID = Users.UserID AND User_Notes.FK_UN_UserID = Users.UserID AND
Job_Assignments.UserID = Users.UserID

WHERE Users.UserID = @UserID AND-- Note.FK_UserID = User_Notes.FK_UN_UserID AND
BackUp_Read = 'Read'

ORDER BY BackUp_Read ASC
END
END
GO


Thanks again

View 12 Replies View Related

Running An UPDATE Statement Only If A Column Exists

Nov 1, 2007

I'm trying to write a script that would only update a column if it exists.

This is what I tried first:

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Enrollment' AND COLUMN_NAME = 'nosuchfield')
BEGIN
UPDATE dbo.Enrollment SET nosuchfield='666'
END

And got the following error:

Server: Msg 207, Level 16, State 1, Line 1
Invalid column name 'nosuchfield'.

I'm curious why MS-SQL would do syntax checking in this case. I've used this type of check with ALTER TABLE ADD COLUMN commands before and it worked perfectly fine.

The only way I can think of to get around this is with:

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Enrollment' AND COLUMN_NAME = 'nosuchfield')
BEGIN
declare @sql nvarchar(100)
SET @sql = N'UPDATE dbo.Enrollment SET nosuchfield=''666'''
execute sp_executesql @sql
END

which looks a bit awkward. Is there a better way to accomplish this?

View 3 Replies View Related

Insert Record If None Exists

Oct 6, 2003

Hello folks,

I am new to msSQL and ASP, I need some help writing an SQL statement that will first check to see if a combination or record exists, if none found thant it will add it. I am working a section of a site that adds favorites to the database. Each user can have more that one favorite hence it has to check for that unique combination of the fields, UserID and FavID

My Code:
Dim objConnection, objRecordset, strSQL
Dim strFavID, strUserID
strFavID = request.Form("favid")
strUserID = request.Form("userid")

Set objConnection = Server.CreateObject("ADODB.Connection")
Set objRecordset = Server.CreateObject("ADODB.Recordset")
objConnection.Open Application("ConnectionString")

strSQL = "INSERT INTO FAV (UserID,FavID) (SELECT DISTINCT " & strUserID & " AS UserID " & _
strFavID & " AS FavID" & " FROM FAV)" & _
" WHERE " & strUserID & " & " & strFavID & " NOT IN (SELECT UserID, FavID FROM FAV)"
response.Write(strSQL)
'response.End()

If strFavID <> "" Then
On Error Resume Next
objConnection.Execute(strSQL)

objConnection.Close
Set objConnection = Nothing
End If


This code is giving me a syntax error, how do I write the correct statement. I am using MS Access 2k

Thanks for your help

View 9 Replies View Related

Don't Insert If Record Exists

Jun 21, 2004

/*if key values exist don't insert new record*/
SELECT

/*if exists don't insert*/
CASE
WHEN ISNULL(gradeId, -1) = -1 THEN
INSERT INTO tblScores
(gtStudentId, assignmentId, score)
VALUES (@nStudent, @nAssignment, 0)
END

FROM tblScores
WHERE gtStudentId = @nStudent AND assignmentId = @nAssignment


tblScores has two fields comprising its primary key (gtStudentId, assignmentId) and the gradeId field is a required filed in this table.

I'm getting syntax errors when I click check syntax (near keywords insert from and end).

one other note: this CASE END is nested inside a BEGIN END loop, is this the problem? Is the 'End" of the 'Case' closing the 'End' of the 'Begin'?

thanks

View 6 Replies View Related

Insert If Not Exists Else Update

Apr 4, 2007

Hello,

it's me again :)
I've got a - what I think - simple question.
There is table A with Col1,Col2,Col3 and Table B with Col1,Col2,Col3

I want all rows from B in A. If a row already exist in A, then update all columns, else just insert the row.
Can someone please help me with a small syntax.
Thank you!

View 6 Replies View Related

Using NOT EXISTS In An INSERT Procedure

Jul 23, 2005

I am using the following code to insert records into a destination tablethat has a three column primary key i.e. (PupilID, TermID &SubjectGroup). The source table records all the pupils in a school with(amongst other things) a column (about 50) for each subject the pupilmight potentially sit. In these columns are recorded the study groupthat they belong to for those subjects. The destination table holds arecord per pupil per subject per term, against which the teacher willultimately record the pupils performance.The code as shown runs perfectly until the operator tries to insert aselection of records that include some that already exist. What I wouldlike it to do is, record those, which do not exist and discard theremainder. However, whenever a single duplicate occurs SQL rejects thewhole batch. I know that my solution will probably involve using the‘NOT EXISTS’ expression, but try as I might I cannot get it to work. Tofurther complicate things, the code is being run from within VBA usingthe RunSQL command.The variables ‘strFieldName’, ‘strGroup’ & ‘strTerm are declared at thestart of the procedure and originate from options selected on an Accessform.INSERT INTO dbo.yInterimReportData (PupilID, LastName, FirstName,TermID, SubjectGroup) SELECT PupilID, LastName, FirstName," & "'" &strTerm & "'" & "," & "'" & strGroup & "'" & "FROM dbo.Pupils WHERE (" &strFieldName & " = " & "'" & strGroup & "')Any Ideas?RegardsColin*** Sent via Developersdex http://www.developersdex.com ***

View 1 Replies View Related

Insert Not Exists Dual PK Problem

Mar 17, 2008

Hi  I am trying to populate a table with 2 FKs as its PK (SiteID and ProductDescID).  First 1) I add in all the products whose Manfacturer and Category are supposed to appear on the site and then 2) I add in all the extra products that are needed regardless of their manufacturer or category.   The problem I am having is if the product has already been added to the ProductCatTable due to its Manufacturer or Cateogry but is also in the SatForceProduct table.  The can’t insert duplicate PK error is thrown.  I don’t know how to do this IF NOT EXISTS statement (or what ever else may be needed) so that I can check whether a line from the Forced table needs to be added.  I am not passing in any parameters and I am expecting more than 1 line to be inserted in each of the statements. Please help -- 1) Populate      INSERT INTO            dbo.ProductCatTable            (SiteID, ProductDescID)             SELECT                dbo.SatSite.SiteID, dbo.ProductDesc.ProductDescID      FROM        dbo.SatManu INNER JOIN        dbo.ProductDesc ON dbo.SatManu.Manu = dbo.ProductDesc.Manu INNER JOIN        dbo.SatCats ON dbo.ProductDesc.Cat = dbo.SatCats.Cat INNER JOIN        dbo.SatSite ON dbo.SatManu.SatID = dbo.SatSite.SiteID AND         dbo.SatCats.SatID = dbo.SatSite.SiteID        2) Add Force Ins  IF NOT EXISTS(SELECT SiteID, ProductDescID FROM ProductCatTable WHERE ????????) BEGIN       INSERT INTO                        dbo. ProductCatTable                                    (SiteID, ProductDescID)       SELECT            SiteID, ProductDescID      FROM         dbo.SatForceProduct        END            Thanks in advance J
 

View 2 Replies View Related

IF Exists UPDATE ELSE INSERT Problem

Feb 18, 2004

Hi,

I have a 'Products' table (with: 'uid' and 'CatName' columns) and 'ProductCategory' table (with: 'uid', 'ProductID', 'CategoryID' columns).

I got stored procedure below to update or insert new row to 'ProductCategory' table whenever 'Products' table has been updated or new products has been added to it.

Update part works just fine but when new row has been added to 'Products' this storedProc dosn't insert it into 'ProductCategory' table, it does that only when 'ProductCategory' table is empty, I'm afraid it's because first column 'uid' in 'ProductCategory' table is an Identity column... I’m not sure how should I go about that problem. This is my stored procedure:

DECLARE @CatNo INT, @CatName varchar(10)
SET @CatNo = 2
SET @CatName = 'bracket'

IF exists (SELECT ProductID from ProductCategory, Products where ProductCategory.ProductID = Products.uid and Products.CatName = @CatName )
BEGIN
UPDATE ProductCategory SET CategoryID = @CatNo
FROM Products WHERE Products.CatName = @CatName and ProductCategory.ProductID = Products.uid
END
ELSE
BEGIN
INSERT INTO ProductCategory ( ProductID, CategoryID)
SELECT uid, @CatNo FROM Products
WHERE Products.CatName = @CatName
END

SET @CatNo = 3
SET @CatName = 'cable'

IF exists (SELECT ProductID from ProductCategory, Products where ProductCategory.ProductID = Products.uid and Products.CatName = @CatName )
BEGIN
UPDATE ProductCategory SET CategoryID = @CatNo
FROM Products WHERE Products.CatName = @CatName and ProductCategory.ProductID = Products.uid
END
ELSE
BEGIN
INSERT INTO ProductCategory ( ProductID, CategoryID)
SELECT uid, @CatNo FROM Products
WHERE Products.CatName = @CatName
END
(... Goes for another 37 categories)



Thank you for help.

Kooba

View 3 Replies View Related

Record Exists Insert Or Update

Oct 25, 2007



I had implemented as in the link to insert or update
http://blogs.conchango.com/jamiethomson/archive/2006/09/12/SSIS_3A00_-Checking-if-a-row-exists-and-if-it-does_2C00_-has-it-changed.aspx


What i want to know is... how can i assume there are no duplicate records.
I used Distinct keyword and queried it showed me all are distint but some where i find some duplicates just don't know why i am having when i look at the data both are exactly same...

Please let me know how can i fix it.
Urgent..

Thanks

View 5 Replies View Related

Checking To See If A Record Exists Else Insert

Apr 30, 2008

I am checking to see if the source record is available in the target table using a lookup transformation and if not found i have to insert this record.
I have connected the error flow of the lookup transformation to the target. I am acheiving expected results, but is this the best practise? I have not connected to the green arrow to any task.

View 6 Replies View Related







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