Visual Foxpro Database Stored Procedure with Oledb Provider - stored-procedures

I am using Visual Foxpro 8.0 database. Below procedure I am using to return records from database on basis of condition matching but it raised error that:
"Function is not implemented."
Foxpro Procedure ------------------------
PROCEDURE FX_Proc_ValidateUser (paramUserName AS Character, paramPassword AS Character)
LOCAL VarUserName AS Character, varXml
VarUserName = IIF(VARTYPE(paramUserName)!="N","",paramUserName)
LOCAL VarPassword AS Character
VarPassword = IIF(VARTYPE(paramPassword)!="N","",paramPassword)
SELECT userinfoid, ;
username, ;
password ;
FROM tm_userinfo.dbf ;
WHERE username = VarUserName AND password = VarPassword ;
INTO CURSOR procResult
varXml = ""
CURSORTOXML("procResult","varXml",1,32,0,"1")
RETURN varXml
ENDPROC
Front End code for calling this procedure------------------
string ConnectionString = "Provider=VFPOLEDB.1;Data Source=C:\Users\raj\Documents\Visual FoxPro Projects\dbFoxMaster.dbc;Collating Sequence=machine;" providerName="System.Data.OleDb.OleDbConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
OledbConnection objOleDbConnection = new OleDbConnection(ConnectionString);
objOleDbConnection.Open();
OleDbCommand objOleDbCommand = new OleDbCommand();
objOleDbCommand.CommandType = CommandType.StoredProcedure;
objOleDbCommand.CommandText = "FX_Proc_ValidateUser";
objOleDbCommand.Connection = objOleDbConnection;
objOleDbCommand.Parameters.Add("paramUserName", OleDbType.Char).Value = "abc";
objOleDbCommand.Parameters.Add("paramPassword", OleDbType.Char).Value = "123";
var xmlString = oOleDbCommand.ExecuteScalar().ToString();
DataTable table = new DataTable();
using (var reader = new StringReader(xmlString))
{
var dataSet = new DataSet();
// creating a dataset from the xml
dataSet.ReadXml(reader);
table = dataSet.Tables[0];
}
How to get resultset from foxpro 8.0 stored procedure using OledbCommand?

It looks like the problem is that you are putting your results into an array and only the first item in the array is being returned. You should change the stored procedure so that it uses a cursor.
VFP9 Example
Here is a stored procedure example from the northwind.dbc:
Here is an example of calling the stored procedure using C#:
var northwindDbcPath = #"C:\Program Files (x86)\Microsoft Visual FoxPro 9\Samples\Northwind\Northwind.dbc";
var connectionString = "Provider=VFPOLEDB.1;Data Source=" + northwindDbcPath;
var table = new DataTable();
using(var connection = new OleDbConnection(connectionString)) {
using(var command = connection.CreateCommand()) {
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "CustOrdersDetail";
command.Parameters.Add("x", 10248);
var adapter = new OleDbDataAdapter(command);
adapter.Fill(table);
}
}
VFP8 Example:
(I don't have a copy of VFP8 but I believe that this will work)
var northwindDbcPath = #"C:\Program Files (x86)\Microsoft Visual FoxPro 9\Samples\Northwind\Northwind.dbc";
var connectionString = "Provider=VFPOLEDB.1;Data Source=" + northwindDbcPath;
DataTable table;
using(var connection = new OleDbConnection(connectionString)) {
using(var command = connection.CreateCommand()) {
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "CustOrdersDetail2";
command.Parameters.AddWithValue("x", 10248);
connection.Open();
// executing stored procedure and getting xml result
var xml = command.ExecuteScalar() as string;
connection.Close();
using(var reader = new StringReader(xml)) {
var dataSet = new DataSet();
// creating a dataset from the xml
dataSet.ReadXml(reader);
table = dataSet.Tables[0];
}
}
}

I have no VFP around and the last time I used VFP it was still version 3.0...
I would try something like this based on the specs here. To learn the rest read-up here
PROCEDURE insertData (pusername, ppassword)
SELECT userinfoid, username, password
FROM tm_userinfo.dbf
WHERE username = pusername AND password = ppassword
INTO ARRAY results
RETURN results
ENDPROC

A Visual Foxpro stored procedure is basically using Visual Foxpro code to perform tasks such as validating columns on insert or update or delete.
For Example, you might add the following code to VFP database stored procedure to validate a "State" column:
PROCEDURE ValidateState()
IF address.state <> [OH]
MESSAGEBOX([Incorrect State value!], 48, [Invalid State])
ENDIF
ENDPROC
For querying a table in a Foxpro database, you may want to look at creating local views. You can do this by right clicking inside the foxpro database and selecting "New Local View", then define your view using the query builder. In the Filter tab, under the "Example" column, you can define parameters using the "?" such as "?pusername".
Here is how you would call the view from your Foxpro code:
LOCAL pusername AS Integer
pusername = "SomeUserName" &&Use this to filter the view
SELECT 0
USE MyViewName &&This will call the view and perform the filter.
You can also make these views updatable and perform your inserts against the view.

Related

MVC Query Result no accept null values

enter image description here Function ListarTipoMascotas() As JsonResult
Dim db As New LQTestDataContext
Dim Listado = From tipomascota In db.TipoMascotas
Where tipomascota.BHABILITADO = 1
Select New With {
.Id = tipomascota.IIDTIPOMASCOTA,
.Nombre = tipomascota.NOMBRE
}
Return New JsonResult With {.Data = Listado,
.JsonRequestBehavior = JsonRequestBehavior.AllowGet
}
End Function
This is my function in VB. MVC , is work fine, but when I have null values the LINQ sent a error.
I'm working with LINQ for my conexion database,
My question is, how I can to do, to this result I can return null values without any problem.
Thank you. I read you.

Is if...exists supported in Snowflake stored procedures?

I have written a stored procedure which will be called from python. The stored procedure needs to insert the variant data into my table if the id doesn't exist or update the existing variant data where there is a match for the id. The id will be passed the way the variant data is, but for now I am just trying to get it working with a hardcoded id. The stored procedure gets called successfully from python, but then nothing gets inserted or updated in the stored procedure and the stored procedure doesn't give me an error. I am not sure if I am doing something wrong or the...
if exists (select * from my_database_table where my_variant_data:id::varchar = '123456')
... part is being ignored because it isn't supported. I haven't been able to find anything in the documentation to prove or disprove this. Does anyone know?
create or replace procedure my_stored_procedure("variant_data" variant)
returns string
language javascript
strict
execute as owner
as
$$
var insert_update_query = `
if exists (select * from my_database_table where my_variant_data:id::varchar = '123456')
begin
update my_database_table SET my_variant_data = parse_json(:1)) WHERE my_variant_data:id::varchar = '123456'
end
else
begin
insert into my_database_table(my_variant_data) select (parse_json(:1));
end
`
var result = "";
try {
var sql_insert_update_query = snowflake.createStatement({
sqlText: insert_update_query
});
var insert_update_query_result = sql_insert_update_query.execute();
result += "\n Query succeeded";
} catch (err) {
result += "\n Query failed failed: " + err.code + "\n State: " + err.state;
result += "\n Message: " + err.message;
result += "\n Stack Trace:\n" + err.stackTraceTxt;
}
return result;
$$
;
I have tested the insert and update parts of the query in the stored procedure individually and they work fine.
Insert - works as expected.
create or replace procedure my_stored_procedure("variant_data" variant)
returns string
language javascript
strict
execute as owner
as
$$
var sql_command = "insert into my_database_table(my_variant_data) select (parse_json(:1));";
var sql = snowflake.createStatement( {sqlText: sql_command, binds:[JSON.stringify(variant_data)]});
var resultSet = sql.execute();
return sql_command;
$$
;
Update - works as expected.
create or replace procedure my_stored_procedure("variant_data" variant)
returns string
language javascript
strict
execute as owner
as
$$
var sql_command = "UPDATE my_database_table SET my_variant_data = parse_json(:1)) WHERE my_variant_data:id::varchar = '123456'";
var sql = snowflake.createStatement( {sqlText: sql_command, binds:[JSON.stringify(variant_data)]});
var resultSet = sql.execute();
$$
;
Given the CODE executed needs to be valid runs on the console SQL, which this if is not, and it is fundamentally a MERGE command I would suggest flipping the code into a MERGE:
MERGE INTO my_database_table USING my_database_table
ON my_variant_data:id::varchar = '123456'
WHEN MATCHED THEN UPDATE SET my_variant_data = parse_json(:1))
WHEN NOT MATCHED THEN INSERT (my_variant_data) VALUES (parse_json(:1));
otherwise if you are want it in SP space, then I would be inclinded to break the code into a SELECT x INTO varaible FROM blar pattern and then have the IF be in SP and pick between the two blocks of SQL to run. But given it's just a merge, I would again still, do a merge.

Entity Framework 6 - Passing Table Valued Parameter to Table Valued Function, returning IQueryable

I want to call a Table Valued Function from entity framework, and have it return an IQueryable. The code I have is:
// Defines table-valued function, which must return IQueryable<T>.
[Function(FunctionType.TableValuedFunction, nameof(ufnGetContactInformation), Schema = dbo)]
public IQueryable<ContactInformation> ufnGetContactInformation(
[Parameter(DbType = "int", Name = "PersonID")]int? personId)
{
ObjectParameter personIdParameter = personId.HasValue
? new ObjectParameter("PersonID", personId)
: new ObjectParameter("PersonID", typeof(int));
return this.ObjectContext().CreateQuery<ContactInformation>(
$"[{nameof(this.ufnGetContactInformation)}](#{nameof(personId)})", personIdParameter);
}
However, I also want to be able to pass into the TVF a Table Valued Parameter (so I can pass a list of Id's into the TVF). I've found code that can do this using a DataTable which references the user-defined type I have in the db, eg:
var dt = new DataTable();
dt.Columns.Add("Id");
dt.Rows.Add(1);
dt.Rows.Add(2);
dt.Rows.Add(3);
var idList = new SqlParameter("idList", SqlDbType.Structured);
warnings.Value = dt;
warnings.TypeName = "dbo.udt_idList";
entities.ExecuteStoredProcedure("usp_TableValuedFunc", idList);
The problem is, the second code uses SQLParameter, and the first code uses ObjectParameter. It appears that ObjectParameter won't allow for user-defined-types to be supplied, and any code EF uses that accepts SQLParameter won't allow me to return an IQueryable from a TVF. Any ideas, am I missing something?

How to execute a dynamic stored procedure that return a table in vb6 recordset and assign Datasource to a spreadgrid

I wrote a dynamic procedure than populate the columns and then use Pivot to show the data.
How to execute this procedure from vb6 and return the content as datasource.
You can use ADO for this, you will need to add a reference to Microsoft ActiveX Data Ojects. The code as I remember (long time since vb6) is something like
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
Dim strConn As String
Dim strSQL As String
Dim strCol1 As String
Dim strCol2 As String
strConn = "[YOUR CONNECTION SRING]" '(see www.connectionstrings.com for help)
conn.Open connStr
strSQL = "[YOUR SQL QUERY]" '(IE. Proc name)
rs.Open strSQL, conn, adOpenStatic, adLockOptimistic
Do While Not rs.EOF
strCol1 = rs.Fields("Col1Name")
strCol1 = rs.Fields("Col2Name")
rs.MoveNext
Loop
If rs.State = adStateOpen Then rs.Close
Set rs = Nothing
If conn.State = adStateOpen Then conn.Close
Set conn = Nothing

Subsonic 3: Strongly typed return value for stored procedures that return mixed results from different tables

Say I have a stored procedure that returns dataSet from 2 different tables. Example:
SELECT Customers.FirstName, Customers.LastName, SUM(Sales.SaleAmount) AS SalesPerCustomer
FROM Customers LEFT JOIN Sales
ON Customers.CustomerID = Sales.CustomerID
GROUP BY Customers.FirstName, Customers.LastName
Is there any way to get a strongly typed list as a result from this stored procedure ? Something like this:
StoredProcedure sp = myDevDB.GetCustomerSales();
List<MyCustomType> resultSet = sp.ExecuteTypedList<MyCustomType>();
How and where do I define the MyCustomType class ? How do I map its properties to the actual table columns ?
Thanks,
Zohrab.
I just created a asp.net web page that does this. Try this:
DataSet ds = new DataSet();
SqlDataAdapter adtp = new SqlDataAdapter(command);
adtp.Fill(ds);
StringBuilder b = new StringBuilder();
b.AppendLine("class " + this.txtSP.Text + "_QueryResult");
b.AppendLine("{");
foreach ( DataColumn c in ds.Tables[0].Columns )
{
b.AppendLine(string.Format("property {0} {1} {{ get; set; }}", c.DataType, c.ColumnName));
}
b.AppendLine("}" + Environment.NewLine);
this.txtResult.Text = b.ToString();
}
catch { }

Resources