• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 208
  • Last Modified:

Updating a Record in a SQL DB from a C# Console

Ok, I was just running some tests and the same record was added again.
I'm trying to figure out how the C# Code is supposed to know what it needs to do to check the ID on the database, look for that record, and if the record exists, then Update. So, it looks like my C# Code is trying to add an ID Value when all it should do is check for existance on DB.
Below is the code in C# and my Stored Procedure. I appreciate any help to remedy the problem code below.
Thanks Experts!
Wally
------------------ C# Code -------------------------
foreach (ManagementObject csObjQueried in csObjSearcher.Get())
                            {
                                try
                                {
                                    sqlCmd2.Parameters.Add("ID", System.Data.SqlDbType.Int).Value = "ID" ;
                                    sqlCmd2.Parameters.AddWithValue("WorkstationName", csObjQueried["Name"]);
                                    sqlCmd2.Parameters.AddWithValue("UserName", csObjQueried["UserName"]);
                                    sqlCmd2.Parameters.AddWithValue("Domain", csObjQueried["Domain"]);
                                    sqlCmd2.Parameters.AddWithValue("WkstnStatus", csObjQueried["Status"]);
                                    //sqlCmd2.Parameters.AddWithValue("WakeUpType", csObjQueried["WakeUpType"]);
                                }
                                catch (Exception ex)
                                {
                                    sw.WriteLine("No Win32_ComputerSystem WMI Data returned for " + client.Wkstn + ".\nError is " +
                                            ex.Message);
                                    sw.Flush();
                                }
                            }
-------------------------------- STORED PROCEDURE --------------------------------
USE WMIDATA
GO
 
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Wally Davis
-- Create date: April 13, 2009
-- Description:	
-- =============================================
 
ALTER PROCEDURE dbo.usp_InsertToWMIDATA
	-- Add the parameters for the stored procedure here
	@ID int,
	@WorkstationName varchar(15),
	@UserName varchar(15),
	@Domain varchar(50),
	@WkstnStatus varchar(10) = NULL,
	@MacAddress varchar(17)
AS
If @WorkstationName is not null
BEGIN
	INSERT INTO Main(WorkstationName, UserName, Domain, WkstnStatus, MacAddress)
	Values (@WorkstationName, @UserName, @Domain, @WkstnStatus, @MacAddress)
	SET @ID = SCOPE_IDENTITY()
END
ELSE
BEGIN
	UPDATE Main 
		SET WorkstationName = @WorkstationName, 
			UserName = @UserName,
			Domain = @Domain, 
			WkstnStatus = @WkstnStatus,
			MacAddress = @MacAddress
	WHERE ID = @ID
END
GO

Open in new window

0
wally_davis
Asked:
wally_davis
  • 6
  • 5
1 Solution
 
käµfm³d 👽Commented:
Why not modify your stored procedure to do the checking?
-- STORED PROCEDURE
 
alter procedure dbo.usp_InsertToWMIDATA
		@ID int,
		@WorkstationName varchar(15),
		@UserName varchar(15),
		@Domain varchar(50),
		@WkstnStatus varchar(10) = NULL,
		@MacAddress varchar(17)
AS
BEGIN
	IF EXISTS (SELECT COUNT(1) FROM Main WHERE ID = @ID)
		UPDATE Main
		SET WorkstationName = @WorkstationName,
		    UserName = @UserName,
		    Domain = @Domain,
		    WkstnStatus = @WkstnStatus,
		    MacAddress = @MacAddress
		WHERE ID = @ID
	ELSE
		INSERT INTO Main (WorkstationName, UserName, Domain, WkstnStatus, MacAddress)
		VALUES (@WorkstationName, @UserName, @Domain, @WkstnStatus, @MacAddress)
END
 
 
// C#
 
foreach (ManagementObject csObjQueried in csObjSearcher.Get())
{
    try
    {
        sqlCmd2.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = "ID" ;
        sqlCmd2.Parameters.AddWithValue("@WorkstationName", csObjQueried["Name"]);
        sqlCmd2.Parameters.AddWithValue("@UserName", csObjQueried["UserName"]);
        sqlCmd2.Parameters.AddWithValue("@Domain", csObjQueried["Domain"]);
        sqlCmd2.Parameters.AddWithValue("@WkstnStatus", csObjQueried["Status"]);
        
        sqlCmd2.CommandType = CommandType.StoredProcedure;
        sqlCmd2.ExecuteNonQuery("dbo.usp_InsertToWMIDATA");
    }
    catch (Exception ex)
    {
        sw.WriteLine("No Win32_ComputerSystem WMI Data returned for " + client.Wkstn + ".\nError is " +
                ex.Message);
        sw.Flush();
    }
}

Open in new window

0
 
wally_davisAuthor Commented:
After updating the code, I get this error "Failed to convert parameter value from a String to a Int32". That must have something to do with passing the ID to @ID as a parameter.
So, I shouldn't pass anything in really.......correct? and if that is correct, how do I adjust the code so that the SP also doesn't expect a Parameter.
0
 
wally_davisAuthor Commented:
Thinking about it again. ID should be = to something shouldn't it? So, if I pass in something to @ID, I think a call or some Select statement should be run to find the ID on the specific workstation before an update could be made.
0
Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

 
käµfm³d 👽Commented:
I took your ID column to be an auto-increment field that would just add 1 every time a record is inserted. Is this correct? If not, what is the ID column for?
0
 
wally_davisAuthor Commented:
Correct, the ID Column is an Identity / PK Column. I understand how the Inserts are working, but, how is the actual C# Code going to hunt down the specific workstation client's Identity ID in order to know what record to update?
0
 
käµfm³d 👽Commented:
Other than ID, which fields are unique to a workstation? Workstation name I presume?
0
 
wally_davisAuthor Commented:
Correct, just the Workstation Name.
0
 
wally_davisAuthor Commented:
Expert never returned to answer my issue. If Expert doesn't respond in 48 hours please delete this question. I will ask this question again in another thread if no response.
0
 
käµfm³d 👽Commented:
My apologies. I was having a rough time figuring out how to set rules to move emails in my email client. I think EE's mail was a victim of this. Back to the issue...


I attached some modifications. Since workstation name is unique, we can identify a record in the database. The id column is auto-generated so we don't need to pass in anything for that.
-- STORED PROCEDURE
 
alter procedure dbo.usp_InsertToWMIDATA
                @WorkstationName varchar(15),
                @UserName varchar(15),
                @Domain varchar(50),
                @WkstnStatus varchar(10) = NULL,
                @MacAddress varchar(17)
AS
BEGIN
        IF EXISTS (SELECT COUNT(1) FROM Main WHERE WorkstationName = @WorkstationName)
                UPDATE Main
                SET UserName = @UserName,
                    Domain = @Domain,
                    WkstnStatus = @WkstnStatus,
                    MacAddress = @MacAddress
                WHERE  WorkstationName = @WorkstationName
        ELSE
                INSERT INTO Main (WorkstationName, UserName, Domain, WkstnStatus, MacAddress)
                VALUES (@WorkstationName, @UserName, @Domain, @WkstnStatus, @MacAddress)
END
 
 
// C#
 
foreach (ManagementObject csObjQueried in csObjSearcher.Get())
{
    try
    {
        sqlCmd2.Parameters.AddWithValue("@WorkstationName", csObjQueried["Name"]);
        sqlCmd2.Parameters.AddWithValue("@UserName", csObjQueried["UserName"]);
        sqlCmd2.Parameters.AddWithValue("@Domain", csObjQueried["Domain"]);
        sqlCmd2.Parameters.AddWithValue("@WkstnStatus", csObjQueried["Status"]);
        
        sqlCmd2.CommandType = CommandType.StoredProcedure;
        sqlCmd2.ExecuteNonQuery("dbo.usp_InsertToWMIDATA");
    }
    catch (Exception ex)
    {
        sw.WriteLine("No Win32_ComputerSystem WMI Data returned for " + client.Wkstn + ".\nError is " +
                ex.Message);
        sw.Flush();
    }
}

Open in new window

0
 
wally_davisAuthor Commented:
kaufmed. I tested it and this allowed Updates to work perfectly. I'll accept your solution but I really need you to answer this other question first with respect to the Workstation being unique. I have not added the "WorkstationName" column in my table to the Table Designer/Indexes...Keys/Column Property as a "Unique" column. Should I add that column as a Unique ID? I would imagine adding it would make sense but there may also be a reason not too. Thanks!
0
 
käµfm³d 👽Commented:
Adding a Unique constraint to your database column ensures that if you try to add a record with a particular Workstation Name, and that name already exists in a record, then you will get an error (which you can catch/handle) when the new record is attempted to be added. There's nothing saying you do or do not have to do it this way, but I would imagine having it might be more beneficial than not. Of course, there will be a little overhead in checking the table for uniqueness when you add records, but I would perceive it as negligible compared to database integrity.

I hope that made sense :)
0

Featured Post

Granular recovery for Microsoft Exchange

With Veeam Explorer for Microsoft Exchange you can choose the Exchange Servers and restore points you’re interested in, and Veeam Explorer will present the contents of those mailbox stores for browsing, searching and exporting.

  • 6
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now