I Want to write a single SP which inserts and updates.
CREATE PROCEDURE sp_NewPassword
@UserName nvarchar(50),
@OldPassword nvarchar(50),
@NewPassword nvarchar(50)
AS
BEGIN
INSERT INTO RGH_ChangePassword(vUserName, vNewPassword) VALUES(@UserName, @NewPassword)
UPDATE RGH_LoginMaster SET vPassword=@NewPassword WHERE vUserName=@vUserName and vPassword=@OldPassword
END
When i tried to create above sp it gives me an error saying
Msg 137, Level 15, State 2, Procedure sp_NewPassword, Line 8
Must declare the scalar variable "@vUserName".
Hello,I am writing a stored procedure that will take data from severaldifferent tables and will combine the data into a single table for ourdata warehouse. It is mostly pretty straightforward stuff, but there isone issue that I am not sure how to handle.The resulting table has a column that is an ugly concatenation fromseveral columns in the source. I didn't design this and I can't huntdown and kill the person who did, so that option is out. Here is asimplified version of what I'm trying to do:CREATE TABLE Source (grp_id INT NOT NULL,mbr_id DECIMAL(18, 0) NOT NULL,birth_date DATETIME NULL,gender_code CHAR(1) NOT NULL,ssn CHAR(9) NOT NULL )GOALTER TABLE SourceADD CONSTRAINT PK_SourcePRIMARY KEY CLUSTERED (grp_id, mbr_id)GOCREATE TABLE Destination (grp_id INT NOT NULL,mbr_id DECIMAL(18, 0) NOT NULL,birth_date DATETIME NULL,gender_code CHAR(1) NOT NULL,member_ssn CHAR(9) NOT NULL,subscriber_ssn CHAR(9) NOT NULL )GOALTER TABLE DestinationADD CONSTRAINT PK_DestinationPRIMARY KEY CLUSTERED (grp_id, mbr_id)GOThe member_ssn is the ssn for the row being imported. Each member alsohas a subscriber (think of it as a parent-child kind of relationship)where the first 9 characters of the mbr_id (as a zero-padded string)match and the last two are "00". For example, given the followingmbr_id values:1234567890012345678901123456789021111111110022222222200They would have the following subscribers:mbr_id subscriber mbr_id12345678900 1234567890012345678901 1234567890012345678902 1234567890011111111100 1111111110022222222200 22222222200So, for the subscriber_ssn I need to find the subscriber using theabove rule and fill in that ssn.I have a couple of ideas on how I might do this, but I'm wondering ifanyone has tackled a similar situation and how you solved it.The current system does an insert with an additional column for thesubscriber mbr_id then it updates the table using that column to joinback to the source. I could also join the source to itself in the firstplace to fill it in without the extra update, but I'm not sure if theextra complexity of the insert statement would offset any gains fromputting it all into one statement. I plan to test that on Monday.Thanks for any ideas that you might have.-Tom.
In VB6 using MDAC 2.8 I could do a single select statement that would act as either an Insert or an update. Is there a way to do this in ADO.net? My old VB6 code Dim dbData As New ADODB.Connection Dim rs1 As New ADODB.Recordset Dim strParm As String Dim strCusNo As String ' strParm = "Provider=SQLOLEDB; Data Source=SQL2000; Initial Catalog=DATA_01; User ID=UserName; Password=password" dbData.Open strParm ' strParm = "Select CusNo from CusFil Where CusNo = '" & strCusNo & "'" rs1.Open strParm, dbData, adOpenStatic, adLockOptimistic, adCmdText If rs1.BOF And rs1.EOF Then rs1.AddNew Else
End If With rs1 !CusNo = strCusNo .Update End With rs1.Close ' Set rs1 = Nothing dbData.Close Set dbData = Nothing
A problem has come up in designing a Web page to maintain a small reference table in SQL Server 2000 (9 columns, about 25 records).
I tried to design the Web page to allow INSERT and UPDATE operations using a single page that posts back to itself. The page contains a set of empty form fields for a new record, followed by a set of filled-in form field for each row in the table. The form fields for existing records are given a unique name based on the field name concatenated with the primary key value for that row.
If I set up the page to INSERT only, it works properly. But when I add the fields for existing records, the INSERT operation malfunctions. Specifically, anytime a set of existing fields for a particular column is added to the page, the INSERT will no longer work properly for that column. This is true for all fields except the primary key field. It always INSERTs correctly. I tried adding only some columns to the set of existing form fields. In that case, the INSERT operation added the correct values for the fields that were not listed in the existing records section, but failed for the others.
I am using the INSERT INTO syntax for that operation and the recordset .Update syntax for the edits. I tried using the recordset .AddNew/.Update syntax for the insert, but it exhibited the same problems. The column data types contain smallint, bit, nvarchar, and ntext types.
I know that the correct values are being put into the INSERT statement. I also tried renaming the INSERT form fields to be totally different than the names of the existing record fields. But the problem comes back no matter what.
If necessary, I can split the logic so that inserts and updates are handled by different pages. But I would like to make this work if possible. If a reader knows why SQL Server is causing this problem, any help would be greatly appreciated.
1.First i need to update the row if the status column is 0 to 1 2.Need to insert the row IF SegmentId=@SegmentId and SubjectId<>@SubjectId and StaffId=@StaffId 3.Need to insert the row IF StaffId<>@StaffId And ClassId=@ClassId and SegmentId<>@SegmentId and SubjectId<>@SubjectId
I have wrote the stored procedure to do this, But the problem is If do the update, It is reflecting in the database by changing 0 to 1. But it shows error like cannot insert the duplicate
I can think of ways to resolve this issue, but I am wondering if there is a standard practice or some setting that is used to ensure that text containing a single quote, such as "Bob's house", is passed correctly to the database when using a SqlDataSource with all of the default behavior. For example, I have a FormView setup with some text fields and a SqlDataSource that is used to do the insert. There is no code in the form currently. It works fine unless I put in text with a single quote, which of course messes up the insert or update. What is the best way to deal with this? Thank you
I would like to update/insert data into a Orderhearder Table along with the related details into the corrosponding OrderDetails Tables. Can this be done using a single stored procedure or do we have to make one call to the UpdateOrderHeader Stored Procedure and loop thru all the details and call the UpdateOrderDetails Stored Procedure. How do we handle the Transactions in such a case ?
1.First i need to update the row if the status column is 0 to 1 2.Need to insert the row IF SegmentId=@SegmentId and SubjectId<>@SubjectId and StaffId=@StaffId 3.Need to insert the row IF StaffId<>@StaffId And ClassId=@ClassId and SegmentId<>@SegmentId and SubjectId<>@SubjectId
I have wrote the stored procedure to do this. But the problem is If do the update. It is reflecting in the database by changing 0 to 1. But it shows error like cannot insert the duplicate
Here is the stored Procedure what i have wrote
ALTER PROCEDURE [dbo].[InsertAssignTeacherToSubjects]
I am hoping someone can shed light on this odd behavior I am seeing running a simple UPDATE statement on a table in SQL Server 2000. I have 2 tables - call them Table1 and Table2 for now (among many) that need to have certain columns updated as part of a single transaction process. Each of the tables has many columns. I have purposely limited the target column for updating to only ONE of the columns in trying to isolate the issue. In one case the UPDATE runs fine against Table1... at runtime in code and as a manual query when run in QueryAnalyzer or in the Query window of SSManagementStudio - either way it works fine. However, when I run the UPDATE statement against Table2 - at runtime I get rowsaffected = 0 which of course forces the code to throw an Exception (logically). When I take out the SQL stmt and run it manually in Query Analyzer, it runs BUT this is the output seen in the results pane... (0 row(s) affected) (1 row(s) affected) How does on get 2 answers for one query like this...I have never seen such behavior and it is a real frustration ... makes no sense. There is only ONE row in the table that contains the key field passed in and it is the same key field value on the other table Table1 where the SQL returns only ONE message (the one you expect) (1 row(s) affected) If anyone has any ideas where to look next, I'd appreciate it. Thanks
If I have a table with 1 or more Nullable fields and I want to make sure that when an INSERT or UPDATE occurs and one or more of these fields are left to NULL either explicitly or implicitly is there I can set these to non-null values without interfering with the INSERT or UPDATE in as far as the other fields in the table?
EXAMPLE:
CREATE TABLE dbo.MYTABLE( ID NUMERIC(18,0) IDENTITY(1,1) NOT NULL, FirstName VARCHAR(50) NULL, LastName VARCHAR(50) NULL,
[Code] ....
If an INSERT looks like any of the following what can I do to change the NULL being assigned to DateAdded to a real date, preferable the value of GetDate() at the time of the insert? I've heard of INSTEAD of Triggers but I'm not trying tto over rise the entire INSERT or update just the on (maybe 2) fields that are being left as null or explicitly set to null. The same would apply for any UPDATE where DateModified is not specified or explicitly set to NULL. I would want to change it so that DateModified is not null on any UPDATE.
INSERT INTO dbo.MYTABLE( FirstName, LastName, DateAdded) VALUES('John','Smith',NULL)
INSERT INTO dbo.MYTABLE( FirstName, LastName) VALUES('John','Smith')
INSERT INTO dbo.MYTABLE( FirstName, LastName, DateAdded) SELECT FirstName, LastName, NULL FROM MYOTHERTABLE
Table Name:-emp table structure:- Name Gender A Male B Male C FeMale D FeMale I want only one update query to update this table like this table structure:- Name Gender A FeMale B FeMale C Male D Male please help me?
querey is--TABLE1 HAS A COLUMN CALLED CITY .THE RECORDS WITH CITY='DELHI' ARE IS TO BE UPDATED WITH CITY='MUMBAI' AND THE RECORDS WITH CITY='MUMBAI' ARE IS TO BE UPDATED WITH CITY='DELHI' ...
i HAVE TO WRITE A SINGLE SQLSTATEMENT TO DO THIS NOT WITH THE HELP OF CURSOR
What is the single SQL statement to truncate the blank space on either side of data. Ex. Table1 has Name as column. I have records filled with blank space on both side for Name field. With one query I want to correct (truncate the leading and trailing space) the data. How? SQL Server 2005 SP2. Thank you, Smith
I have a web form with a text field that needs to take in as much as the user decides to type and insert it into an nvarchar(max) field in the database behind. I've tried using the new .write() method in my update statement, but it cuts off the text after a while. Is there a way to insert/update in SQL 2005 this without resorting to Bulk Insert? It bloats the transaction log and turning the logging off requires a call to sp_dboptions (or a straight-up ALTER DATABASE), which I'd like to avoid if I can.
I need to write a single query that will append the values from one table into another table but I need to update a single field in the table with a static value. What I'm working with is an Access .adp with an SQL 2000 backend. The database is used to track ticket sales, payments, and contact info for season ticket holders. Prior to upsizing, each year the database would be copied and then choice bits modified for the next year.
In other words, the history was in several databases, i.e. db2001, db2002, db2003 and for the current year dbcurrent. I decided to create a historic tables in the current DB rather than have umpteen DBs on my SQL server.
My problem is that I need to create a query that appends to my table the previous years data and then updates the season field to reflect the season that the data came from.
In short, say I have a table named accounts with fields account, customer, addr1, addr2, ..., ticket type and I want it to end up in account_hist with fields account, customer, addr1, addr2, ..., ticket type, SEASON and make the season equal say 8 which represents the 8th season the team has played. I can get both queries to work seperately :D , but for end user ease, I want to perform both actions at the same time :confused: . Can anybody point me in the right direction? Thanks
I'm collecting id based on user's selection and storing to ArrayList/String[in asp.net]. Now want to pass those ids stored to stroed procedure. I want SP to update all records in single statement using in like update table set field in (value).
I'm storing id with comma (,) separator. Below is my asp.net code:
string sId=string.Empty;
for(int a=0;a<Id.Count;a++)
{
Id += Id;
if(a!=Id.Count-1)
sId +=",";
}
In database id column is int type. I'm passing id collected with comma separator and passing it as a parameter to SP. but it is giving error related converting to int or similar.
Plz help me create Stored Procedure in SQL 2005 based on above scenario.
I'm working on inserting data into a table in a database. The table has two separate triggers, one for insert and one for update (I don't like it this way, but that's how it's been for years). When there is a normal insert, done via a program, it looks like the triggers work fine. When I run an insert manually via a script, the first insert trigger will run, but the update trigger will fail. I narrowed down the issue to a root cause.
This root issue is due to both triggers using the same temporary table name. When the second trigger runs, there's an error stating that a few columns don't exist. I went to my test server and test db and changed the update trigger so that the temporary table is different than the insert trigger temporary table, the triggers work fine. The weird thing is that if the temporary table already exists, when the second trigger tries to create the temporary table, I would expect it to fail and say that it already exists.I'm probably just going to update the trigger tonight and change the temporary table name.
When users enter text into a textbox, to be INSERTed into my table, SQL Server throws an error if their text contains a single quote. For example, if they enter "It's great!" then it causes this error:Error: Incorrect syntax near 's'. Unclosed quotation mark after the character string ''. How can I allow text with single quotes to be inserted into the table?
My code results in SQL statements like the following one - and it gives an error because of the extra single-quotes in 'it's great': UPDATE Comments SET Comment='it's great' WHERE UserID='joe' AND GameID='503' Here's the error I get when I try this code in SQL Server: Msg 102, Level 15, State 1, Line 1Incorrect syntax near 's'.Msg 105, Level 15, State 1, Line 1Unclosed quotation mark after the character string ''. I need to know how I can insert a string such as 'it's great' - how do I deal with the extra quotes issue? is there a way to ecape it like this 'it/'s great' ? This doesn't seem to work. Here's the code that generates the SQL. I'm using a FCKeditor box instead of a TextBox, but I got the same error when I was using the TextBox: string strUpdate = "UPDATE Comments SET Comment='";strUpdate = strUpdate + FCKeditor1.Value;//strUpdate = strUpdate + ThisUserCommentTextBox.Text;strUpdate = strUpdate + "' WHERE UserID='";strUpdate = strUpdate + (string)Session["UserID"];strUpdate = strUpdate + "'";strUpdate = strUpdate + " AND GameID='";strUpdate = strUpdate + Request.QueryString["GameID"];strUpdate = strUpdate + "'"; SqlConnection myConnection = new SqlConnection(...);SqlCommand myCommand = new SqlCommand(strUpdate, myConnection); try{myCommand.Connection.Open();myCommand.ExecuteNonQuery();}catch (SqlException ex){ErrorLabel.Text = "Error: " + ex.Message; }finally{myCommand.Connection.Close();}
I'm using SQL Server 2005 and ASP.NET 2.0 Much thanks
Hi, I am beginer to ASP.NET. I want to insert ' ( single quote ) which is entered by the user in a textbox of the ASP.NET web page. As you all know in the insert command the column is ending at that single quote.
I have a problem with inserting a string with single quotes. For instance, string testme = "we don't have anything"; insert into tableone (buff) values ("'" + testme + "'"); I get an error with the word "don't" with single quote. But if I delete the single quote "dont" then it inserts okay. Is is a bug in sql 2005? Please help. Thanks. blumonde
Got a beginner question here... Let's say I have a database table that houses server information with four columns: make, model, serial #, ip address. And assume there are ten rows with that information filled out. How could I display all the rows of information on a single webpage (ASP.NET), with all the fields being editable; and a single save button that would send any changes to the database (in reality I guess it would be sending all rows and fields to the database, and just overwrite the previous data).
Could a page such as that be created using FrontPage 2003 or Dreamweaver MX 2004?
This would be strictly for updating information. I would have a separate form for adding a new entry.
I get a timeout expired error when running the following in a vb component.
'update cm_event_notification Set processed = '3/29/01 9:46:01 AM' Where dn = '{2E738808-23B4-11D5-B49A-00508BD934F8}'
The table dn column is a primary key, when I run it from sql Anyalzer it works. If there are two rows to update it works, just the single row update times out!
update a tables value(a single column), based on a query of another database, using a common column.
Here's what I've cooked up so far:
Declare @trackingNo nvarchar (50) Set @trackingNo = ( select tracking_no from P21_Shipping.dbo.shipping_data t1 inner join P21.dbo.oe_hdr t2 on t1.order_no = t2.order_no
[Code] ...
print @trackingNoThe error it's returning is:
Msg 512, Level 16, State 1, Line 3 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
So, I'm wanting to query Shipping_data for order_No that matches the same orderNo column value in P21 Database(oe_hdr table), then update P21 oe_hdr table with "trackingNo from Shipping_data