SQL Results Not Returned to C# - asp.net-mvc

SETUP:
asp.net MVC
SQL SERVER 2008 R2
I have a procedure to get a list of messages to send. I want to update the results records so I cannot accidentally pull the same records twice. Regardless of how I approach it, SSMS produces the correct list of messages. However, if I update the records in the same procedure, C# does not get any results.
I have tried using a DataAdapter like this:
var da = new SqlDataAdapter(cmd);
da.Fill(table);
and DataReader like this:
var dataReader = cmd.ExecuteReader();
table.Load(dataReader);
dataReader.Close();
to populate my DataTable, neither seems to affect the results.
My procedure looks like this:
ALTER PROCEDURE [dbo].[MnxNoticeGetMessages]
#sessionId uniqueidentifier = null
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Output TABLE (messageid uniqueidentifier)
INSERT INTO #Output
SELECT messageid FROM MnxTriggerEmails WHERE dateSent is null
SELECT * FROM MnxTriggerEmails WHERE messageid IN (SELECT messageid FROM #Output)
UPDATE MnxTriggerEmails SET dateSent=GETDATE()
WHERE messageid IN (SELECT * FROM #Output)
END
This produces results in SSMS but not in C#.
If I comment out the UPDATE like this (no other changes):
--UPDATE MnxTriggerEmails SET dateSent=GETDATE()
-- WHERE messageid IN (SELECT * FROM #Output)
I get the expected results in both SSMS and C#.
What am I missing? What would cause this? How do I update the records AND get the results at the same time?

Your code looks fine. It should work. It almost sounds like you are calling the sp twice. The first time changes the dates and the second returns no results. This would cause ssms to produce the desired results and c# to be empty.
Check the code you haven't posted and see if you make that call again before populating the DataTable.

Related

Snowflake Tasks causing error in timezone in queries

I am running a simple insert query inside a stored procedure with to_timeatamp_ntz("column value") along with other columns.
This works fine when I am running it with the snowflake UI and logged in with my account.
This works fine when I am calling it using python scripts from my visual studio instance.
The same stored procedure fails when it is being called by a scheduled task.
I am thinking if it has something to do with the user's timezone of 'System' vs my time zone.
Execution error in store procedure LOAD_Data(): Failed to cast variant
value "2019-11-27T13:42:03.221Z" to TIMESTAMP_NTZ At
Statement.execute, line 24 position 57
I tried to provide timezone as session parameters in task and in the stored proc but does not seem to be addressing the issue. Any ideas?
I'm guessing (since you didn't include the SQL statement that causes the error) that you are trying to bind a Date object when creating a Statement object. That won't work.
The only parameters you can bind are numbers, strings, null, and the special SfDate object that you can only get from a result set (to my knowledge). Most other parameters must be converted to string using mydate.toJSON(), JSON.stringify(myobj), etc., before binding, eg:
var stmt = snowflake.createStatement(
{ sqlText: `SELECT :1::TIMESTAMP_LTZ NOW`, binds: [(new Date).toJSON()] }
);
Date object errors can be misleading, because Date objects causing an error can be converted and displayed as strings in the error message.
I found the issue:
my Task was using a copy paste effect similar to this:
CREATE TASK TASK_LOAD_an_sp
WAREHOUSE = COMPUTE_WH
TIMEZONE = 'US/Eastern'
SCHEDULE = 'USING CRON 0/30 * * * * America/New_York'
TIMESTAMP_INPUT_FORMAT = 'YYYY-MM-DD HH24'
AS
Call LOAD_an_sp();
The Timestamp input format was causing this.

How to create an update query with Open Office Base?

I want to create basically an update query on Open Office Base (the same way with Ms ACCESS).
Base does not typically use update queries (but see below). Instead, the easiest way to do an update command is to go to Tools -> SQL. Enter something similar to the following, then press Execute:
UPDATE "Table1" SET "Value" = 'BBB' WHERE ID = 0
The other way is to run the command with a macro. Here is an example using Basic:
Sub UpdateSQL
REM Run an SQL command on a table in LibreOffice Base
Context = CreateUnoService("com.sun.star.sdb.DatabaseContext")
databaseURLOrRegisteredName = "file:///C:/Users/JimStandard/Desktop/New Database.odb"
Db = Context.getByName(databaseURLOrRegisteredName )
Conn = Db.getConnection("","") 'username & password pair - HSQL default blank
Stmt = Conn.createStatement()
'strSQL = "INSERT INTO ""Table1"" (ID,""Value"") VALUES (3,'DDD')"
strSQL = "UPDATE ""Table1"" SET ""Value"" = 'CCC' WHERE ID = 0"
Stmt.executeUpdate(strSQL)
Conn.close()
End Sub
Note that the data can also be modified with a form or by editing the table directly.
Under some circumstances it is possible to create an update query. I couldn't get this to work with the default built-in HSQLDB 1.8 engine, but it worked with MYSQL.
In the Queries section, Create Query in SQL View
Click the toolbar button to Run SQL Command directly.
Enter a command like the following:
update mytable set mycolumn = 'This is some text.' where ID = 59;
Hit F5 to run the query.
It gives an error that The data content could not be loaded, but it still performs the update and changes the data. To get rid of the error, the command needs to return a value. For example, I created this stored procedure in MYSQL:
DELIMITER $$
CREATE PROCEDURE update_val
(
IN id_in INT,
IN newval_in VARCHAR(100)
)
BEGIN
UPDATE test_table SET value = newval_in WHERE id = id_in;
SELECT id, value FROM test_table WHERE id = id_in;
END
$$
DELIMITER ;
Then this query in LibreOffice Base modifies the data without giving any errors:
CALL update_val(2,'HHH')
See also:
https://forum.openoffice.org/en/forum/viewtopic.php?f=5&t=75763
https://forum.openoffice.org/en/forum/viewtopic.php?f=61&t=6655
https://ask.libreoffice.org/en/question/32700/how-to-create-an-update-query-in-base-sql/
Modifying table entries from LibreOffice Base, possible?

SSIS Script Component Call Stored Procedure returns -1

I tried implementing a call to Stored proc and the proc returns ID which will used later.
Everytime I execute I get the out parameter as -1. Below is my sample code:
OleDbCommand sqlStrProc = new OleDbCommand();
sqlStrProc.Connection = dbConn;
sqlStrProc.CommandText = "dbo.insert_test";
sqlStrProc.CommandType = CommandType.StoredProcedure;
sqlStrProc.Parameters.Add("#p_TestID", OleDbType.Integer, 255).Direction = ParameterDirection.Output;
sqlStrProc.Parameters.Add("#p_TestName", OleDbType.VarChar).Value = "Test";
sqlStrProc.Parameters.Add("#p_CreatedBy", OleDbType.VarChar).Value = "Test";
int personID = sqlStrProc.ExecuteNonQuery();
Row.outPersonID = personID;
personID is always -1. What am I doing wrong here. Please help..!!
Below is the stored proc code
CREATE PROCEDURE [dbo].[INSERT_TEST]
#p_TestID int OUTPUT,
#p_TestName varchar (50),
#p_CreatedBy varchar (100)
AS
SET NOCOUNT ON
INSERT INTO Test(
TestName,
CreatedBy)
VALUES
( #p_TestName,
#p_CreatedBy)
SELECT #p_TestID = SCOPE_IDENTITY()
-1 could mean that the stored procedure failed to execute as desired and the transaction was rolled back. You may want to look for any truncation issues since you have different sizes for the 2 input parameters but are using the same input. Also I assume you have proper code to open and close connections etc?
-1 returned value is an error produced during the execution of your SP, this is due to the following reasons:
SP Structure: everytime you are executing the SP it tries to create it again while it already exists. so you have to either make it an ALTER PROCEDURE instead of CREATE PROCEDURE or do the following:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[INSERT_TEST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[INSERT_TEST]
GO
CREATE PROCEDURE [dbo].[INSERT_TEST]
#p_TestID int OUTPUT,
#p_TestName varchar (50),
#p_CreatedBy varchar (100)
AS
Database Connection (Table Name and Location): you have to specify withe the OLEDB the ConnectionString that connects you to the write DB. try to test the full Table path; like the following;
INSERT INTO [DATABASENAME].[SHCEMA].[TABELNAME](
Name,
CreatedBy)
VALUES
( #p_TestName,
#p_CreatedBy)
Define your SP as :
CREATE PROCEDURE [NAME]
AS
BEGIN
END
thought it is not a problem, but it is a proper way to write your SPs in terms of connection transactions,
Let me know if it works fine with you :)
Regrads,
S.ANDOURA

What's wrong in Classic ASP StoredProcedure insert statement

Here is the classic ASP code
Set objCommandSec = CreateObject("ADODB.Command")
With objCommandSec
Set .ActiveConnection = MyConn
.CommandType = adCmdStoredProc
.CommandText = "ReportsPDFInsert"
.CreateParameter "#StatsID", adInteger, adParamInput
.Parameters("#StatsID") = xStats_ID
.CreateParameter "#MemberID", adInteger, adParamInput
.Parameters("#MemberID") = xMemberID
.CreateParameter "#LanguageID", adInteger, adParamInput
.Parameters("#LanguageID") = 1 '1=EN
.CreateParameter "#PDFFilename", adVarWChar , adParamInput
.Parameters("#PDFFilename") = PDFFilename
.Execute
End With
Here is the stored procedure code
ALTER PROCEDURE [dbo].[ReportsPDFInsert]
-- Add the parameters for the stored procedure here
#StatsID INT
,#MemberID INT
,#LanguageID INT
,#PDFFilename NVARCHAR(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO [dbo].[ReportsPDF]
([StatsID]
,MemberID
,[LanguageID]
,[PDFFilename]
,[DateCreated])
VALUES
(#StatsID
,#MemberID
,#LanguageID
,#PDFFilename
,GETDATE())
END
I get error as
Error number: -2147217904
Error description: Procedure 'ReportsPDFInsert' expects parameter '#StatsID', which was not supplied.
Source: Microsoft OLE DB Provider for SQL Server
If I execute the stored procedure itself, then it is working fine. I have similar classic asp code in other page, and that works fine as well. yes, I made sure xStats_ID does have value. I printed just before the .Execute and I see the value.
Please somebody shed some light. Thanks
Try appending the parameters explicitly using something like this:
cmd.Parameters.Append cmd.CreateParameter("#StatsID",adInteger, adParamInput,xStats_ID)
instead of .Parameters("")
Here is another post that might help:
How to make a parametrized SQL Query on Classic ASP?
Only today I figured what was the problem.
I haven't included the adovbs.inc file for the constants to work.
And I don't know why it was throwing some other error message.
good reason to move away from Classic ASP [only if my boss listens]
Try dropping the "#" in your parameter names.

How to retrieve a value from a recordset that is not a return value or output parameter using vb6

I have a stored proc on an existing 3rd party application (SQL 2005) that I wish to interact with.
It is an insert statement followed by a select statement as follows;
Set #CustomerId = Cast(SCOPE_IDENTITY() As [int])
Select #CustomerId
Using VB6 how do I access the value of #CustomerID?
set rs = cmd.Execute
is not returning a resultset as expected...
[Edit]
rs.Fields.Count is 0.
Any attempt to access the resulting recordset, like rs(0).Value simply causes an "Item not found..." error.
I would guess that your stored procedure is returning more than one recordset.
If this is the case, you can use the NextRecordset() method to iterate through them.
MSDN:
If a row-returning command executes successfully but returns no records,
the returned Recordset object will be
open but empty. Test for this case by
verifying that the BOF and EOF
properties are both True.
If a non–row-returning command executes successfully, the returned
Recordset object will be closed, which
you can verify by testing the State
property on the Recordset.
When there are no more results, recordset will be set to Nothing.
This means I would suggest something like this to solve your problem:
Set rs = cmd.Execute
''# fetch the first value of the last recordset
Do Until rs Is Nothing
If rs.State = adStateOpen Then
If Not (rs.BOF And rs.EOF) Then
''# You can do a different sanity check here, or none at all
If rs.Fields(0).Type = adInteger Then
CustomerId = rs.Fields(0).Value
End If
End If
End If
Set rs = rs.NextRecordSet
Loop
MsgBox CustomerId

Resources