Updating Specific Columns Through A Stored Procedure At Runtime

Feb 25, 2008

I have a question. I know its possible to create a dynamic query and do an exec @dynamicquery. Question: Is there a simpler way to update specific columns in a table at run time without doing if else for each column to determine which is null and which has a value because i'm running into a design dilemna on how to go about it.

FYI: All columns in the table design are set to null by default.

Thanks in advance,

Dimeji

View 4 Replies


ADVERTISEMENT

Updating Specific Columns If That Column Is Equal To A Value In One Query?

Dec 8, 2006

I want to set a column to 0 if it is set to a certain number. There are several columns to check though, so I am wondering if I can do it all in one query, or if I have to do it in single queries?

here is an example:

account | contact_id_1 | contact_id_2 | contact_id_3
433 | 67 | 23 | 67

so I want to set any contact_id_N = 0 where contact_id_N is = 67

so in the end, the table will look like this:

account | contact_id_1 | contact_id_2 | contact_id_3
433 | 0 | 23 | 0

is there a way to do it in one statement?

View 2 Replies View Related

Run Stored Procedure In Specific Database

Jul 20, 2007

I have created a stored procedure in the master database that can be run against any database on the server.
I call this procedure from a sql server agent job. In this job I specify the database I want the procedure to run against but it always seems to run against the master database (presumably because the procedure is in this database). I can't switch database inside the procedure so what can I do other than creating a copy of the procedure in every database?

View 4 Replies View Related

Updating A Value In A Stored Procedure

Dec 12, 2007

I have a batch input system consisting of two tables which I've simplified below.
 
(Batch Table)BatchID   IntBatchTotal  Decimal(18.2)
(BatchTran Table)BatchTranID  IntBatchTranHeaderID Int   This links to BatchID BatchTranValue  Decimal(18.2)BatchTranAccountNo Int
 
When the batch is complete I want to move the details from the Batch files and transfer them to the relevant Accounts files.
 
(Account Table)AccountNoID  IntAccountTotal  Decimal(18.2)
(AccountTran Table)AccountTranBatchID IntAccountTranBatchRef IntAccountTranAmount Decimal(18.2)
 
I want to be able to run a stored procedure which selects all Batches and Transactions with a reference passed to the stored procedure (@BatchID) and create the entries in the AccountTran Table
 INSERT INTO AccountTran(AccountTranBatchID, AccountTranBatchRef, AccountTranAmount) SELECT  BatchTranId, BatchTranHeaderID, BatchTranValue FROM BatchTran WHERE BatchTranHeaderID=@BatchID
No problems so far, the details are created perfectly.
 
What I want to do next is to take the values in BatchTranValue (which have been passed into AccountTranAmount) and add it to AccountTotal field
My question is can this be completed in one stored procedure if so can you guide me as to how I achieve this?
 
Many thanks

View 3 Replies View Related

Stored Procedure Not Updating

Jun 5, 2006

Using VS.Net 2003 and C#
Why won't this update the table?
public bool changeVisibility( string Id, bool visibility )
{
using( SqlConnection conn = new SqlConnection( @SQLHelper.CONN_STRING ) )
{
using( SqlCommand command = new SqlCommand( "changeVisibility", conn ) )
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add( "@Id", Id );
command.Parameters.Add( "@visibility", visibility );
<snip>
And then the stored procedure:
CREATE PROCEDURE dbo.changeVisibility
 @Id           VARCHAR(20),  @visibility         BIT
 ASBEGIN BEGIN TRAN      UPDATE courseStructure  SET    visible = @visibility                       WHERE  Id = @Id  
 COMMIT TRAN
 ENDGO
The @visibility seems to be the problem.
I set it in the code as boolean.  And it goes into the sp as a BIT.
This should work but doesn't.
If I change the SET visible = 0 it works ok, but not with @visibility.
Thanks,
Zath

View 4 Replies View Related

T-SQL (SS2K8) :: Call Stored Procedure And Obtain Specific Results

Apr 17, 2014

I have a few questions about the following t-sql 2008 r2 sql code listed below that is calling a stored procedure:

DECLARE@return_value int,
@endYear SMALLINT = 2014,
@CustomerID INT = '9999',
@Schedules CHAR(1) = N'C'

EXEC [dbo].[sproom] @endYear
,@CustomerID
,@Schedules

The sql listed above does execute the stored procedure called [dbo].[sproom] successfully and returns all the data all the rows from the stored procedure multiple times. However can you tell me the following:

1. How can I have the stored procedure return distinct rows?
2. I want the stored procedure to return selected columns. I tried using the OUTPUT parameter for some of the columns, but I got the error message, "Procedure or function spHomeroom has too many arguments specified.".

when I change the sql above to:

DECLARE @return_value int,
@endYear SMALLINT = 2014,
@CustomerID INT = '9999',
@Schedules CHAR(1) = N'C',
@CustName varchar(50)
EXEC [dbo].[sproom] @endYear
,@CustomerID
,@Schedules
,@CustName

That is when I get the error message.

A solution might be to change the stored procedure, but I would prefer not to since this is a generic stored procedure that I believe a lot of t-sqls and stored procedures will use.

View 3 Replies View Related

T-SQL (SS2K8) :: Run Block In Stored Procedure Only During Specific Time Frame

May 11, 2015

I have a stored procedure that runs every 5 minutes. I have one block in the procedure that will only run if there are records in a temp table. In addition, I would like this block to run only if the current time is between 0 and 5 minutes past the hour or between 30 and 35 minutes past the hour.

Currently, my block looks like this:
IF OBJECT_ID('tempdb..#tmpClosedPOs') IS NOT NULL
BEGIN

I can get the current minutes of the current time by using:

Select DATEPART(MINUTE,GetDate())

I know that it should be simple, but I'm pretty new at Stored Procedures. How do I alter the IF statement to check for the time and only run the block if it's between the times I stated? I started to DECLARE @Minutes INT, but wasn't sure where to go from there.

View 7 Replies View Related

Updating A View Through A Stored Procedure.

Oct 14, 2007

Hi i have a page in which a user fills out info on a page, the problem i am getting is that when the save button is clicked all text box values apart from one are saving to the database this field is the "constructor_ID" field. The save button performs a stored procedure, however there is a view which is doing something as well, would it be possible to write a stored procedure which would update the view at the same time?
CREATE PROCEDURE sp_SurveyMainDetails_Update
@Constructor_ID  int,@SurveyorName_ID int,@Survey_Date char(10),@Survey_Time char (10),@AbortiveCall bit,@Notes  text,@Survey_ID int,@User_ID int,@Tstamp timestamp out AS
 
DECLARE @CHANGED_Tstamp timestampDECLARE @ActionDone char(6)SET @ActionDone = 'Insert'
SET @CHANGED_Tstamp = (SELECT Tstamp FROM tblSurvey WHERE Survey_ID = @Survey_ID)IF @Tstamp <> @CHANGED_Tstamp --AND @@ROWCOUNT =0 BEGIN  SET @Tstamp =  @CHANGED_Tstamp  RAISERROR('This survey has already been updated since you opened this record',16,1)  RETURN 14 ENDELSE
   BEGIN
SELECT * FROM tblSurvey WHERE  Constructor_ID   = @Constructor_ID   AND  --Contractor_ID  = @Contractor_ID  AND  Survey_DateTime = Convert(DateTime,@Survey_Date + ' ' + LTRIM(RTRIM(@Survey_Time)), 103) AND  IsAbortiveCall = @AbortiveCall     IF @@ROWCOUNT>0                          SET @ActionDone = 'Update'
UPDATE tblSurvey SET    Constructor_ID   = @Constructor_ID   ,  SurveyorName_ID   = @SurveyorName_ID ,     Survey_DateTime = Convert(DateTime,@Survey_Date + ' ' + LTRIM(RTRIM(@Survey_Time)), 103) ,  IsAbortiveCall = @AbortiveCall ,  Note  = @Notes               WHERE Survey_ID = @Survey_ID AND Tstamp = @Tstamp IF @@error = 0 begin                        exec dhoc_ChangeLog_Insert    'tblSurvey',  @Survey_ID,  @User_ID,  @ActionDone,  'Main Details',  @Survey_ID
    end else BEGIN  RAISERROR ('The request has not been proessed, it might have been modifieid since you last opened it, please try again',16,1)  RETURN 10   END SELECT * FROM tblSurvey WHERE Survey_ID=@Survey_ID     
END
--Make sure this has saved, if not return 10 as this is unexpected error
--SELECT * FROM tblSurvey
DECLARE @RETURN_VALUE tinyintIF @@error <>0 RETURN @@errorGO
 This is the view;
CREATE VIEW dbo.vw_Property_FetchASSELECT     dbo.tblPropertyPeriod.Property_Period, dbo.tblPropertyType.Property_Type, dbo.tblPropertyYear.Property_Year, dbo.tblProperty.Add1,                       dbo.tblProperty.Add2, dbo.tblProperty.Add3, dbo.tblProperty.Town, dbo.tblProperty.PostCode, dbo.tblProperty.Block_Code, dbo.tblProperty.Estate_Code,                       dbo.tblProperty.UPRN, dbo.tblProperty.Tstamp, dbo.tblProperty.Property_ID, dbo.tblProperty.PropertyStatus_ID, dbo.tblProperty.PropertyType_ID,                       dbo.tblProperty.Correspondence_Add4, dbo.tblProperty.Correspondence_Add3, dbo.tblProperty.Correspondence_Add2,                       dbo.tblProperty.Correspondence_Add1, dbo.tblProperty.Correspondence_Phone, dbo.tblProperty.Correspondence_Name,                       dbo.tblPropertyStatus.Property_Status, dbo.tblProperty.Floor_Num, dbo.tblProperty.Num_Beds, dbo.vw_LastSurveyDate.Last_Survey_Date,                       dbo.tblProperty_Year_Period.Constructor_ID, dbo.tblProperty_Year_Period.PropertyPeriod_ID, dbo.tblProperty_Year_Period.PropertyYear_ID,                       LTRIM(RTRIM(ISNULL(dbo.tblProperty.Add1, ''))) + ', ' + LTRIM(RTRIM(ISNULL(dbo.tblProperty.Add2, '')))                       + ', ' + LTRIM(RTRIM(ISNULL(dbo.tblProperty.Add3, ''))) + ', ' + LTRIM(RTRIM(ISNULL(dbo.tblProperty.PostCode, ''))) AS Address,                       dbo.tblProperty.TenureFROM         dbo.tblPropertyType RIGHT OUTER JOIN                      dbo.tblProperty LEFT OUTER JOIN                      dbo.tblProperty_Year_Period ON dbo.tblProperty.Property_ID = dbo.tblProperty_Year_Period.Property_ID LEFT OUTER JOIN                      dbo.vw_LastSurveyDate ON dbo.tblProperty.Property_ID = dbo.vw_LastSurveyDate.Property_ID LEFT OUTER JOIN                      dbo.tblPropertyStatus ON dbo.tblProperty.Status_ID = dbo.tblPropertyStatus.PropertyStatus_ID ON                       dbo.tblPropertyType.PropertyType_ID = dbo.tblProperty.PropertyType_ID LEFT OUTER JOIN                      dbo.tblPropertyPeriod ON dbo.tblProperty.PropertyPeriod_ID = dbo.tblPropertyPeriod.PropertyPeriod_ID LEFT OUTER JOIN                      dbo.tblPropertyYear ON dbo.tblProperty.PropertyYear_ID = dbo.tblPropertyYear.PropertyYear_ID
   
 

View 1 Replies View Related

Update Stored Procedure Not Updating

Apr 12, 2008

Hello,I'm working on a grant management database for a project in my databases class and I'm having some issues updating grants into the database.Here is my situation:How this page works is, it gets a query string from a search_grant.aspx page.  In this query string, it gets the grant ID of the grant the user wants to edit.  If the grant id is a valid grant, it then, upon page_load in C#:1.) Creates an Sql connection set to a viewGrant stored procedure,2.) Adds in all the necessary parameters as output variables3.) Sets private members declared inside of the partial class to those values it gets from the stored procedure4.) Sets textbox controls on the page to those values5.) Displays the page with all the populated data from the stored procedureThat part works fine.  I was having an issue where clicking the update button would not grab the new values that the user input into the textboxes.  I later realized that the Page_Load code was being re-executed BEFORE the button was being clicked (kind of dumb but...whatever).  To fix it, I placed all of the code to do the above statements inside of a: if (!Page.IsPostBack){ // Do code here}That works fine.  The problem, however, is that it's STILL not updating.  The stored procedure works just fine inside of the management studio, but not in the ASP Page.  The code is similar to that of my new_grant.aspx page, which creates a grant into the database.  Why that works and this doesn't, I don't know.  Even when I hard code the values into the parameters in C#, it's not updating the data!  There are no errors that are being returned, so this has really boggled my mind.Any help is greatly appreciated! Here is some sample code of what I'm doing:protected void Update_button_Click(object sender, EventArgs e){ // Create SQL connection to update Grant string ConnectionString = "connection string which works fine"; SqlConnection sqlConnection2 = new SqlConnection(); try { sqlConnection2.ConnectionString = ConnectionString; sqlConnection2.Open(); } catch (Exception Ex) { if (sqlConnection2 != null) { sqlConnection2.Dispose(); } SQLErrorLabel.Text = Ex.Message; SQLErrorLabel.Visible = true; return; } // ------------------ Update values into database ------------------- // Create the statement to use on the database SqlCommand editGrant = new SqlCommand("editGrant", sqlConnection2); editGrant.CommandType = CommandType.StoredProcedure; editGrant.Connection = sqlConnection2; // Set our values for each variable GrantName = GrantName_input.Text; ProjectDescription = ProjDesBox.Text; ReportingYear = Int32.Parse(ReportYearBox.SelectedItem.ToString()); ActivityStarted = Activity_Date.Text; DateSubmitted = Date_Submitted.Text; Audit = chkAudit.Checked; TypeID = Type_ID_input.SelectedValue; FunderID = Funder_List.SelectedValue; StatusID = Status_ID_input.SelectedValue; AcademicDepartmentID = AcademicID_List.SelectedValue; PIID = PI_List.SelectedValue; ContractNumber = txtContractNum.Text; ESUAccountNumber = txtESUAccountNum.Text; AmountAwarded = txtAmount.Text; AwardDate = Award_Date.Text; DateContractSigned = txtDateSigned.Text; ReportingNotes = ReportingNotesbox.Text; NotesNotes = GrantNotesbox.Text; string ReportingTimestamp = DateTime.Now.ToString(); string ReportingWho = Membership.GetUser().ToString(); string NotesTimestamp = DateTime.Now.ToString(); string NotesWho = Membership.GetUser().ToString(); #region insertParams // Add our parameters that SQL will be using editGrant.Parameters.AddWithValue("@GrantID", GID); editGrant.Parameters["@GrantID"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@GrantName", GrantName); editGrant.Parameters["@GrantName"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@ProjectDescription", ProjectDescription); editGrant.Parameters["@ProjectDescription"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@ReportingYear", ReportingYear); editGrant.Parameters["@ReportingYear"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@ActivityStarted", ActivityStarted); editGrant.Parameters["@ActivityStarted"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@DateSubmitted", DateSubmitted); editGrant.Parameters["@DateSubmitted"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@Audit", Audit); editGrant.Parameters["@Audit"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@TypeID", TypeID); editGrant.Parameters["@TypeID"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@StatusID", StatusID); editGrant.Parameters["@StatusID"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@FunderID", FunderID); editGrant.Parameters["@FunderID"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@AcademicDepartmentID", AcademicDepartmentID); editGrant.Parameters["@AcademicDepartmentID"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@PIID", PIID); editGrant.Parameters["@PIID"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@ContractNumber", ContractNumber); editGrant.Parameters["@ContractNumber"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@ESUAccountNumber", ESUAccountNumber); editGrant.Parameters["@ESUAccountNumber"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@AmountAwarded", AmountAwarded); editGrant.Parameters["@AmountAwarded"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@AwardDate", AwardDate); editGrant.Parameters["@AwardDate"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@DateContractSigned", DateContractSigned); editGrant.Parameters["@DateContractSigned"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@ReportingNotes", ReportingNotes); editGrant.Parameters["@ReportingNotes"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@ReportingTimestamp", ReportingTimestamp); editGrant.Parameters["@ReportingTimestamp"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@ReportingWho", ReportingWho); editGrant.Parameters["@ReportingWho"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@NotesNotes", NotesNotes); editGrant.Parameters["@NotesNotes"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@NotesTimestamp", NotesTimestamp); editGrant.Parameters["@NotesTimestamp"].Direction = ParameterDirection.Input; editGrant.Parameters.AddWithValue("@NotesWho", NotesWho); editGrant.Parameters["@NotesWho"].Direction = ParameterDirection.Input; #endregion // Execute the UPDATE statement to Grant editGrant.ExecuteNonQuery(); sqlConnection2.Close(); sqlConnection2.Dispose(); Response.Redirect("editedGrant.aspx?id=" + GrantIDBox.Text);}EDIT: Problem Solved! Problem was the that the GrantID wasn't being properly set.

View 6 Replies View Related

Stored Procedure For Updating A Table

Jul 10, 2013

I have a table Patient_Registration with columns Patient_ID,Registration_Date,RENEWAL_DATE_D

After billing This table will get updated every time , when there is any new patient registered or any old patient got renewed there account.

For New patient registration the service code is 1.
and for renewed patient the service code is 293.

CREATE PROCEDURE [dbo].[SP_UPDATE_PATIENT_REGISTRATION_RENEW_DATE]
@PID BIGINT
AS
BEGIN
UPDATE PATIENT_REGISTRATION SET RENEWAL_DATE_D = (SELECT top 1 BD.BILL_DATE_D

[Code] .....

View 3 Replies View Related

SSIS XML Configuration Updating At Runtime

Jun 26, 2006

How can I update a variable in the XML configuration file. Can I use the configuration object for it or do I need to use XML objects and do it just like any other XML file?

Another problem I have is, I know I can reference the same XML config file from 2 different packages. But every time I do that through the wizard, only the last package configurations are placed in the XML file.

Any help is appreciated!

 

View 8 Replies View Related

Stored Procedure For Updating Bit Datatype Column

Mar 25, 2008

Hi guys,
I have a table with following columns and records.
Empid       Empname        Phone     Flag
14             Rajan                 2143          116             Balan                 4321          122             Nalini                 3456          023             Ganesh              9543          0
Now i need to create a stored procedure which will convert the flag values to vice versa since it is a bit datatype. That is if execute the stored procedure it should convert all the flag values to 1 if it zero and zero's to 1. How? Pls provide me the full coding for the stored procedure.
Thanx. 

View 2 Replies View Related

Trouble Updating SQLTable Using A Stored Procedure

Jan 30, 2004

If I run a update stored procedure on my SQLServer It work Fine.
But When I try it in my VB code, it's just do nothing not even an error message.

What I've got to do for being able to Update SQLTable with a stored procedure?

That's my VB code:


Dim objConnect As SqlConnection
Dim strConnect As String = System.Configuration.ConfigurationSettings.AppSettings("StringConn")

objConnect = New SqlConnection(strConnect)

Dim objCommand As New SqlCommand("internUpdate", objConnect)
objCommand.CommandType = CommandType.StoredProcedure

Try
Dim objParam As SqlParameter

objParam = objCommand.Parameters.Add("Id", SqlDbType.Int)
objParam.Direction = ParameterDirection.Input
objParam.Value = InternIDValue

objParam = objCommand.Parameters.Add("Address", SqlDbType.VarChar, 50)
objParam.Direction = ParameterDirection.Input
objParam.Value = Address.Value.Trim()

objParam = objCommand.Parameters.Add("City", SqlDbType.VarChar, 50)
objParam.Direction = ParameterDirection.Input
objParam.Value = City.Value.Trim()

objParam = objCommand.Parameters.Add("ProvinceCode", SqlDbType.Char, 2)
objParam.Direction = ParameterDirection.Input
objParam.Value = myProvince.SelectedValue

objParam = objCommand.Parameters.Add("PostalCode", SqlDbType.VarChar, 50)
objParam.Direction = ParameterDirection.Input
objParam.Value = PostalCode.Value.Trim()

objParam = objCommand.Parameters.Add("Phone", SqlDbType.VarChar, 50)
objParam.Direction = ParameterDirection.Input
objParam.Value = Phone1.Value.Trim()

objParam = objCommand.Parameters.Add("Phone2", SqlDbType.VarChar, 50)
objParam.Direction = ParameterDirection.Input
objParam.Value = Phone2.Value.Trim()

objParam = objCommand.Parameters.Add("Email", SqlDbType.VarChar, 50)
objParam.Direction = ParameterDirection.Input
objParam.Value = EmailAddress1.Value.Trim()

objParam = objCommand.Parameters.Add("Email2", SqlDbType.VarChar, 50)
objParam.Direction = ParameterDirection.Input
objParam.Value = EmailAddress2.Value.Trim()

objParam = objCommand.Parameters.Add("EmploymentStatusCode", SqlDbType.Char, 2)
objParam.Direction = ParameterDirection.Input
objParam.Value = myStatus.SelectedValue

objConnect.Open()
objCommand.ExecuteNonQuery()
objConnect.Close()

Catch ex As Exception
Exit Sub
End Try



Thanks!!

View 1 Replies View Related

Updating 2 Table At The Same Time Using Stored Procedure

Sep 14, 2004

G'day everyone...

I have two tables: Category and Product.
CategoryID is the Foreign Key of Product table.
I want to update those tables at the same time using stored procedure.

It will work like this.
If I update the Display column of Category table to have the value of 0, it will also update any records in the Product table -that has the same CategoryID- to have the value of 0 in its Display column.

I just read something about trigger and bit gives me idea that I might use it for this case, but don't know how to write the SQL.

Can anyone please help me...
Thanks...

View 2 Replies View Related

Access Crashes When Updating A Stored Procedure

Jul 20, 2005

Hello,I am having a problem when using access xp as a frontend for sql server2000.I have been trying to update a number of stored procedures (Just simpleadding fields etc) which results in access crashing with event ID 1000 and1001.Does anyone have any ideas as to what could be the problem?Thanks in advance..

View 3 Replies View Related

Stored Procedure Not Updating Database (no Errors Appearing)

Dec 1, 2003

Hi All,

I have a stored procedure (works form the SQL side). It is supposed to update a table, however it is not working, please help. What is supposed to happen is I have a delete statement deleting a payment from the payment table. When the delete button is pushed a trigger deletes the payment from the payment table and transfers it to the PaymentDeleted table. The stored procedure is supposed to update the PaymentDeleted table with the empID and reason for deleting, the delete and transfer work fine, however these 2 fields are not updated. Below is the sp and below that is the vb code. Thanks, Karen



ALTER PROCEDURE dbo.PaymentDeletedInfoTrail (@EmpID_WhoDeleted varchar(10), @Reason_Deleted varchar(255), @PmtDeletedID int)
AS
BEGIN

UPDATE dbo.PaymentDeleted
SET EmpID_WhoDeleted = @EmpID_WhoDeleted
WHERE PmtDeletedID = @PmtDeletedID

UPDATE dbo.PaymentDeleted
SET Reason_Deleted = @Reason_Deleted
WHERE PmtDeletedID = @PmtDeletedID

END



Private Sub cmdSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
Me.Validate()
If Me.IsValid Then
Dim DR As SqlClient.SqlDataReader

Dim strPmtID As String
strPmtID = lblPmtIDDel.Text

Dim MySQL As String
MySQL = "DELETE From Payment WHERE PmtID = '" & strPmtID & "'"
Dim MyCmd As New SqlClient.SqlCommand(MySQL, SqlConnection1)
SqlConnection1.Open()
DR = MyCmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
SqlConnection1.Close()


Dim strDeletePmt As String
strDeletePmt = lblPmtIDDel.Text

Dim cmd As New SqlClient.SqlCommand("PaymentDeletedInfoTrail", SqlConnection1)
cmd.CommandType = CommandType.StoredProcedure

Dim myParam As SqlClient.SqlParameter
myParam = cmd.Parameters.Add(New SqlClient.SqlParameter("@PmtDeletedID", SqlDbType.Int))
myParam.Direction = ParameterDirection.Input
myParam.Value = lblPmtIDDel.Text

myParam = cmd.Parameters.Add(New SqlClient.SqlParameter("@EmpID_WhoDeleted", SqlDbType.VarChar))
myParam.Value = txtEmpIDDelete.Text

myParam = cmd.Parameters.Add(New SqlClient.SqlParameter("@Reason_Deleted", SqlDbType.VarChar))
myParam.Value = txtDeleteComments.Text

SqlConnection1.Open()
cmd.ExecuteNonQuery()
SqlConnection1.Close()

End If
Response.Redirect("PaymentVerification.aspx")
End Sub

View 1 Replies View Related

Stored Procedure Definition Not Updating, Causing DTS Copy Error

Jun 27, 2007

I've got a weird one here. I'm running a DTS package on SQL Server2005. It copies a bunch of stored procedures. I renamed them on theoriginating server and ran the DTS again.The came over with the old name and code!I deleted the DTS and built it from scratch, and the same thinghappened.I ran SELECT * FROM sys.objects where type = 'P' on the source serverand the names were correctI'm explicitly checking which sp to copy rather than using Copy all. Ican see the sp namesI've deleted and recreated the sp on the source server using scriptsI've checked the source server nameI've Refreshed everywhereNothing worksWhy is up_Department_GetAllBySchool trying to be be pulled over whenit doesn't exist?Why is up_Department_GetBySchool not being pulled over when it doesexist?I've heard that SQL 2005 pre-SP2 has a problem where renaming anobject that has a text definition (like sprocs, functions, triggers,views) doesn't update the definition. So if you pull that objectdefinition and run it into your new database, it will use the originalscript, which has the original name.I ransp_helptext 'up_Department_GetBySchool'and checked the CREATE statement at the top. Sure enough, it had theold textI asked our NetAdmin to install SP2 on our server. Then I ransp_refreshsqlmodule 'up_Department_GetForSchool'and got this error:Invalid object name 'up_Department_GetAllForSchool'.So even the code which was supposed to fix it, doesn't. Has anyoneelse had this problem, and managed to fix it?--John Hunter

View 1 Replies View Related

Updating A Specific Cell In An Excel From Sql

Sep 25, 2006

Is there a way to update a specific cell(s) in an excel? I have an excel with charts and graphs which use as data source a range of cells from another sheet within the same spreadsheet. Is there a way update a specific cell from within the sql using openrowset()... ?

thanks

View 1 Replies View Related

Updating By Default/specific Values

Apr 5, 2007

In my datawarehouse fact table I have a column (revenue) that I want to populate based on the values of number of columns, for simplicity, say just 2 columns, 'productid' and 'affiliateid'.

I have a revenue lookup table, with those same 2 columns and the amount. So far so simple, but rather than have one row for every possible combination, I use 0 to mean default. For instance, all the affiliates have the same revenue value apart from a couple, so instead of 200 rows identical except for the affiliateid, I have one row with a '0' for the affiliateid and 4 rows with specific affiliateIDs where it differs from the default.

E.G.

AffiliateID, TypeID, Revenue
0, 1, £50
22, 1, £55
33, 1, £57
0,2,£60
22, 2, £66
33, 2, £69


To update the values, I join to the revenues table twice, one for both columns matching, and once for the default. I.E.

UPDATE facttable SET revenue = ISNULL(rev1.revenue, ISNULL(rev2.revenue,0))
FROM facttable FT
LEFT OUTER JOIN revenues rev1 ON FT.AffiliateID = rev1.AffilateID and FT.TypeID = rev1.TypeID
LEFT OUTER JOIN revenues rev2 ON rev1.AffilateID = 0 and FT.TypeID = rev1.TypeID
(In fact, this is over-simplified, because in fact there are 3 columns, so I have to have 8 joins like this).

This works very well, and cuts down the management of revenues significantly, there are a few 100 rows instead of the more than 100,000 there would be if I put every possible combination of values in its own row.

However, now there is a requirement to increase the granularity of the revenue allocation up to 5 columns, which makes 36 joins and there could well be more columns added later.

Has anyone come across a situation like this (and found a neater solution).

View 2 Replies View Related

Stored Procedure Columns?

May 23, 2008

I have set up an OLEDB data source with Command Text that calls a stored procedure. The rows and columns of data appear correctly when I preview the data but no external columns are available for mapping to output columns.

I was hoping to call the stored procedure and output the resulting data to an Excel destination. Am I tryig to do sornething that can't be done?

Thanks,

*** Campbell

View 8 Replies View Related

Updating Specific Col's Based On Data Availablity

Jul 20, 2007

Hi,

DONT KNOW IF IT IS POSSIBLE.. PLEASE SUGGEST.

Currently working on a upload module where in the data from excel file is imported to the destination tables. Data in the excel sheet comes in phases. All excel sheet columns data don't come at first shot. The excel sheet's data is dumped into temporary tables which inturn is looped using cursor's and gets finally updated to the actual tables.

Now, the problem I am facing is how do I update columns of the actual table with the data (i.e NON NULL values) available in the temporary table without tampering the data allready present in actual table.

Ideally what required is, update the actual table column values with the corresponding columns of temporary table ONLY for Non NUll column values of temporary table.

Temporary and Destination tables have 85 columns each. I don't want to write 85 update queries.

The scenario which I am facing is given below with 2 columns as an example.


1. Table 1 :- tbl_source (Temporary Table) has two columns src_Col1 & src_Col2
2. Table 2 :- tbl_destination (Actual Table) has two columns dest_Col1 & des_Col2


Scenario -1
---------------

tbl_Source Sample Data (after excel import to the temporary table)
------------------------

src_Col1 src_Col2
------------------
50 NULL


tbl_Destination Sample Data
------------------------

dest_Col1 dest_Col2
------------------
50 NULL



Scenario -2
---------------

tbl_Source Sample Data
------------------------

src_Col1 src_Col2
------------------
NULL 100


tbl_Destination Sample Data
------------------------

dest_Col1 dest_Col2
------------------
50 100


One update query which handles both scenarios.


Thanking you in anticipation.

Regards

View 4 Replies View Related

Any Way To Find Out Which SP Is Updating Data In A Specific Table?

Sep 22, 2005

Can you create an UPDATE TRIGGER and use some typeof code to figure out which SP just updated the current table?If not how can i achieve what i want?I tried to run SQL Profiler and i don't understand why i can'tsimply have the Profiler filter events only for the specific database idand the table's object id i chose?What am i doing wrong with SQL Profiler? I was testing thisthrough SQL EM. I had the filters chosen for a specific database idand a specific table's object id, yet when i open another table SQLProfiler captures that information too.Thank you

View 2 Replies View Related

Updating A Specific Amount Of Records In A Table

Jun 20, 2007

I have a table with 35,000 records in it. I want to update a value in column A for only the first 5000 records, leaving the value in Column A for the remaining 30,000 records as it is now. What would be the command I would use to update Column A for the first 5000 records.

Thanks,

View 4 Replies View Related

Cannot Find Columns From A Stored Procedure...

Jul 21, 2007

I have an application that I inherited, and I have a annoying problem.  We're using stored procedures to return most of our data, and occasionally we receive errors stating that a particular column cannot be found in the resulting data table.  When I run the stored procedure against SQL Server I receive the expected output.  What would make this random act happen, any ideas?
Also, I keep receiving errors stating that a connection is already open and needs to be closed before an action to the database is performed.  I'm explicitly closing each connection in a finally block for every method in my data access code, so a connection should always be closed, right?

View 3 Replies View Related

Define Stored Procedure Columns

Apr 22, 2008

The SQL below is the start of a massive Stored Procedure for Comparing two Datasets, which will be produced onto a report.

I was wondering if I could call an SQLserver Procedure that would tell me the names of all the Columns that are produced by this SP, so I can print them out and more easily code the report?


SELECT
stk.StockNumber,
stk.DefaultImageName,
tVTP.Make as PolMake,
stkV.VehicleMake,
tVTP.Model as PolModel,
stkV.VehicleModel,
tVTP.ModelNo as PolModelNo,
stkV.VehicleModelNo,
tVTP.EngineNumber as PolEngineNumber,
Stk.EngineNumber,
tVTP.comHeadLightNumber as PolHeadLightNumber,
Stk.comHeadLightNumber,
tVTP.comTailLightNumber as PolTailLightNumber,
Stk.comTailLightNumber ,
tVTP.comBumperLightNumber as PolBumperLightNumber,
Stk.comBumperLightNumber,
tVTP.comCornerLightNumber as PolCornerLightNumber,
Stk.comCornerLightNumber,
tVTP.Chassis as PolChassis,
--Drive Train
tVD.DriveTrainDescription as POlDriveTrainDescription,
StktVD.DriveTrainDescription,
--Body Type
tVBT.BodyTypeDescription as PolBodyDescription ,
StkVBT.BodyTypeDescription


FROM tblStock Stk
--JOINS FOR THE Policy Definition
INNER JOIN tblVehicles V
ON V.VehicleID = Stk.VehicleID
INNER JOIN tblVehicleType_Policy tVtP
ON tVTP.VehicleMaster = V.VehicleMaster
AND tVTP.Make = V.VehicleMake
AND tVTP.Model = V.VehicleModel
AND tVTP.ModelNo = V.VehicleModelNo
INNER JOIN tblVehicleDriveTrain tVD ON
tVD.vehicleDrivetrainID = tVTP.DrivetrainID
INNER JOIN tblvehicleBodyType tVBT ON
tVBT.VehicleBodyTypeID = tVTP.BodyTypeID


--JOINS FOR the Stock Definition
INNER JOIN tblVehicles STkV ON
StkV.VehicleID = Stk.VehicleID
INNER JOIN tblvehicleBodyType StkVBT ON
StkVBT.VehicleBodyTypeID = Stk.BodyTypeID
INNER JOIN tblVehicleDriveTrain StktVD ON
StktVD.vehicleDrivetrainID = stk.DrivetrainID

--INNER JOIN tbl
WHERE Stk.StockNumber LIKE 'V%'

View 6 Replies View Related

Remove Columns Stored Procedure

May 6, 2007

Just wondering if i could get some help with this,

I have a large table of decimal values, many of the columns contain only zero values. I would like to write a
stored procedure which loops through these columns, takes the SUM and if it returns zero , then deletes the column from the table.

Any help would be appreciated, thanks in advance, this site has already helped me heaps

View 14 Replies View Related

Stored Procedure To Update Columns

Sep 2, 2006

Hello,I've written an insert trigger to fill in data on 5 columns based on the keyfield column after a record is added to a table. The trigger works fine.But what I also want to do is to write a stored procedure that will updatethe 5 columns for the entire table based on the table key field column. I'mnew to both triggers and stored procedures and I can't figure out how tomake a stored procedure do what I want.Can someone help me to get me started? Here is the trigger code that I amtrying to get to work as a stored procedure. All I'm trying to do is tobreak up an entry that contains dashes into separate fields that aredelimited by the dashes. As an example if field CABLENO is equal toI-IJB-200-45, then I want to break that up into 4 separate fields containingI, IJB, 200, 45 respectively.Thanks,Al Willis--------------------------------------------------------------------------------------------------------IF EXISTS (SELECT NAME FROM SYSOBJECTS WHERE NAME='CABLE_SEGMENTS' AND TYPE='TR')DROP TRIGGER IM.CABLE_SEGMENTSGOCREATE TRIGGER CABLE_SEGMENTSON IM.CAB_MFOR INSERTASDECLARE @CABLENO_REMAIN VARCHAR(40),@DASH_POS SMALLINT,@SEG1 VARCHAR(40),@SEG2 VARCHAR(40),@SEG3 VARCHAR(40),@SEG4 VARCHAR(40),@SEG5 VARCHAR(40)SELECT @CABLENO_REMAIN = CABLENO FROM INSERTEDSELECT @SEG1 = NULLSELECT @SEG2 = NULLSELECT @SEG3 = NULLSELECT @SEG4 = NULLSELECT @SEG5 = NULLSELECT @DASH_POS = CHARINDEX('-',@CABLENO_REMAIN)IF @DASH_POS 0BEGINSELECT @SEG1 = SUBSTRING(@CABLENO_REMAIN,1,@DASH_POS-1)SELECT @CABLENO_REMAIN = SUBSTRING(@CABLENO_REMAIN,@DASH_POS+1,40)SELECT @DASH_POS = CHARINDEX('-',@CABLENO_REMAIN)IF @DASH_POS 0BEGINSELECT @SEG2 = SUBSTRING(@CABLENO_REMAIN,1,@DASH_POS-1)SELECT @CABLENO_REMAIN = SUBSTRING(@CABLENO_REMAIN,@DASH_POS+1,40)SELECT @DASH_POS = CHARINDEX('-',@CABLENO_REMAIN)IF @DASH_POS 0BEGINSELECT @SEG3 = SUBSTRING(@CABLENO_REMAIN,1,@DASH_POS-1)SELECT @CABLENO_REMAIN =SUBSTRING(@CABLENO_REMAIN,@DASH_POS+1,40)SELECT @DASH_POS = CHARINDEX('-',@CABLENO_REMAIN)IF @DASH_POS 0BEGINSELECT @SEG4 = SUBSTRING(@CABLENO_REMAIN,1,@DASH_POS-1)SELECT @CABLENO_REMAIN =SUBSTRING(@CABLENO_REMAIN,@DASH_POS+1,40)SELECT @SEG5 = @CABLENO_REMAINENDELSESELECT @SEG4 = @CABLENO_REMAINENDELSESELECT @SEG3 = @CABLENO_REMAINENDELSESELECT @SEG2 = @CABLENO_REMAINENDELSESELECT @SEG1 = @CABLENO_REMAINUPDATE IM.CAB_M SET CABLESEG1 = @SEG1,CABLESEG2 = @SEG2,CABLESEG3 =@SEG3,CABLESEG4 = @SEG4,CABLESEG5 = @SEG5FROM INSERTED INSWHERE IM.CAB_M.CABLENO = INS.CABLENOGO--------------------------------------------------------------------------------------------------------

View 2 Replies View Related

How Can Your Reference Columns In A System Stored Procedure

Nov 5, 2002

I want to have a Stored procedure call another stored procedure gathering the info from some of the information SP#1 and use it calling SP#2...
For example sp_Help returns columns when executed (Name, Owner, Object_type).
So how can I reference the Name column and pass it to SP#2

Exec sp_Help

...?
SP#2 name=sp_help.Name ???


Thanks


Richard

View 1 Replies View Related

SQL Server Stored Procedure&#39;s Result Columns

Aug 4, 1999

How can I find the result columns from code? Visual J++ Seems to be able to do that. ADO doesn't want to do it for me, neither does ODBC's SQLProcedureColumns().

Any solutions?

View 1 Replies View Related

Ssis Cannot Pull Columns From Stored Procedure?

Sep 6, 2007



hi,

i have the following stored proc which returns a resultset at the end, i have an SSIS package that calls this stored proc and outputs the result to a file. However, the package fails because it cannot pull the columns for the schema because of the return lines in the middle of the stored proc. If i remove the it works fine, pulls hte columns as normal. but if i leave them in ssis cannot get the columns. what can i do to get around this?



ALTER PROCEDURE [dbo].[uspCreateBrightPointFile]

AS

SET nocount ON

IF EXISTS (SELECT TOP 1 *

FROM brightpointfile)

TRUNCATE TABLE brightpointfile

-- Get the order information from the database where vendorconfirmationID = 0

INSERT INTO brightpointfile

SELECT o.orderid,

o.requestid,

'295193' AS araccountnumber,

o.orderdate,

'PRIORITY' AS shipmethod,

'Asurion Dobson' AS billname,

'PO Box 110808' AS billaddress1,

'Attn Account Receivable' AS billaddress2,

' ' AS billaddress3,

'Nashville' AS billcity,

'TN' AS billstate,

'37222' AS billzip,

c.fullname AS shipname,

Replicate(' ',100) AS shipaddress1,

Replicate(' ',100) AS shipaddress2,

' ' AS shipaddress3,

Replicate(' ',40) AS shipcity,

' ' AS shipstate,

Replicate(' ',10) AS shipzip,

'1' AS linenumber,

ve.sku AS itemcode,

o.quantity AS qty,

r.typeid,

r.customerid,

0 AS addressfound

FROM [order] o WITH (NoLock)

JOIN request r WITH (NoLock)

ON o.requestid = r.requestid

JOIN customer c WITH (NoLock)

ON r.customerid = c.customerid

JOIN (SELECT [subequipid],

[subid],

[clientequipid],

[serialno],

[statusid],

[startdate],

[enddate],

[createdate],

[createuserid]

FROM subequip s1 WITH (NoLock)

WHERE s1.statusid = 1

AND s1.startdate = (SELECT MAX(s2.startdate)

FROM subequip s2 WITH (NoLock)

WHERE s2.statusid = 1

AND s2.subid = s1.subid)) se

ON r.subid = se.subid

JOIN vendorequip ve WITH (NoLock)

ON se.clientequipid = ve.clientequipid

JOIN clientequip ce WITH (NoLock)

ON ce.clientequipid = se.clientequipid

WHERE vendorconfirmationid IS NULL -- order was never sent to CellStar

AND ve.typeid IN (1) -- only pull direct fulfillment (not store fulfillment)

AND ve.vendorid IN (2) -- only pull vendor = CellStar Insurance

AND o.orderdate > '2007-08-01' -- only pull orders after 08/01/2007

--IF @@ERROR <> 0

--RETURN 1

--First use the address types of 2

UPDATE brightpointfile WITH (ROWLOCK)

SET shipaddress1 = b.address,

shipaddress2 = b.address2,

shipcity = b.city,

shipstate = b.stateid,

shipzip = b.zipcode,

addressfound = 1

FROM customeraddress a WITH (NOLOCK),

address b WITH (NOLOCK)

WHERE a.customerid = brightpointfile.customerid

AND b.addressid = a.addressid

AND a.typeid = 2

--IF @@ERROR <> 0

--RETURN 2

--Update the rest where the address type is 1 and there is no type 2

UPDATE brightpointfile WITH (ROWLOCK)

SET shipaddress1 = b.address,

shipaddress2 = b.address2,

shipcity = b.city,

shipstate = b.stateid,

shipzip = b.zipcode

FROM customeraddress a WITH (NOLOCK),

address b WITH (NOLOCK)

WHERE a.customerid = brightpointfile.customerid

AND b.addressid = a.addressid

AND a.typeid = 1

AND brightpointfile.addressfound = 0

--IF @@ERROR <> 0

--RETURN 3

--Select all the records from the temp table, plus union in 2 extra records required by the client

SELECT *

FROM (SELECT orderid,

requestid,

araccountnumber,

orderdate,

shipmethod,

billname,

billaddress1,

billaddress2,

billaddress3,

billcity,

billstate,

billzip,

shipname,

shipaddress1,

shipaddress2,

shipaddress3,

shipcity,

shipstate,

shipzip,

1 AS linenumber,

itemcode,

qty,

0 AS additional

FROM Brightpointfile WITH (nolock)

UNION ALL

SELECT orderid,

requestid,

araccountnumber,

orderdate,

shipmethod,

billname,

billaddress1,

billaddress2,

billaddress3,

billcity,

billstate,

billzip,

shipname,

shipaddress1,

shipaddress2,

shipaddress3,

shipcity,

shipstate,

shipzip,

brightpointdefaultsku.linenumber,

brightpointdefaultsku.sku,

1,

1 AS additional

FROM Brightpointdefaultsku WITH (nolock),

Brightpointfile WITH (nolock)) a

ORDER BY orderid,

additional

IF @@ERROR <> 0

RETURN 1

RETURN 0

View 3 Replies View Related

Stored Procedure To Get All Users Or All Users Of A Specific Country

Apr 30, 2008

hi alli've got two tables called "webusers" (id, name, fk_country) and "countries" (id, name)
at the meantime, i've a search-page where i can fill a form to search users. in the dropdown to select the country i included an option which is called "all countries".
now the problem is: how can i make a stored procedure that makes a restriction to the fk_country depending on the submitted fk_country parameter?it should be something like
SELECT * FROM webusers(if @fk_country > 0, which is the value for "all countries"){    WHERE fk_country = @fk_country}
who has an idea how to solve this problem?

View 9 Replies View Related

Query Names Of Stored Procedure Results Columns?

Mar 2, 2012

I am imagining something you might pass the names of 2 stored procs (an old version and new one), and a query to produce valid parameters. It would then fire off each proc for a set number of executions, while storing off the results in temp tables, and at the end it would do a data compare, and store off performance data from dynamic management views.

Now I know how to get the parameters for a stored procedure out of the catalogue views, but is SQL Server aware at all of the schema of the results of stored procedures that return result sets, becuase I was thinking of doing something like...

INSERT INTO #datacompare(col1,col2)
EXEC mystoredprocedure

... but I can not seem to figure out how to dynamically gather the schema of the result set.

View 1 Replies View Related

SQL Server Admin 2014 :: Updating Statistics On Specific Indices Script

Aug 8, 2015

I'm looking for a quick script that someone has already written to update statistics (not to rebuild or re-organise) on specific indices in specific databases - I guess loop though a table comprising of a list of databases and the indices.

I know Ola has one but I'm not look for something that is that complicated. If I cannot find one I'm going to have to write one myself - I want to try and avoid re-inventing the wheel as tomorrow I have to do this work and it's about 7K plus indices in about 10+ databases.

View 2 Replies View Related







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