ASP.Net MVC - Insert and Update - sql-server

I'm trying to insert and update into my database but I don't know how to use SQL in this context. Was following iamtimcorey on YouTube: https://www.youtube.com/watch?v=bIiEv__QNxw&t=2322s
Business Logic (EmloyeeProcessor)
public static int CreateEmployee(string Employee_number, string First_name, string Last_name,
string Email, string Research_Area, string Position_held,
string Highest_qualification, string Department_name)
{
Employee_Model data = new Employee_Model
{
Employee_number = Employee_number,
First_name = First_name,
Last_name= Last_name,
Email = Email,
Research_area = Research_Area,
Position_held = Position_held,
Highest_qualification = Highest_qualification,
Department_name = Department_name,
};
string sql = #"DECLARE #var_Department_id int;
SELECT #var_Department_id = Department_id
FROM dbo.Departments
WHERE dbo.Departments.Department_name = #Department_name;
INSERT INTO dbo.Employee (Employee_number, First_name, Last_name, Email, Research_area, Position_held, Highest_qualification, #var_Department_id)
VALUES (#Employee_number, #First_name, #Last_name, #Email, #Research_area, #Position_held, #Highest_qualification, #Department_name);";
return SqlDataAccess.SaveData(sql, data);
}
Department_name = Department_name returns a string that's already present in the Department's Table. Department name is a string in table Departments. I want to pass in the matching Department_id from that table into the New Employee I'm creating.
public static class SqlDataAccess
{
public static string GetConnectionString(string connectionName = "DemoDB")
{
return ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
}
public static List<T> LoadData<T>(string sql)
{
using (IDbConnection cnn = new SqlConnection(GetConnectionString()))
{
return cnn.Query<T>(sql).ToList();
}
}
}

I think the SQL-query should look like this:
DECLARE #var_Department_id int;
SELECT #var_Department_id = Department_id
FROM dbo.Departments
WHERE dbo.Departments.Department_name = #Department_name;
/*
Final insert into table dbo.Employee.
*/
INSERT INTO dbo.Employee (
Employee_number,
First_name,
Last_name,
Email,
Research_area,
Position_held,
Highest_qualification,
Department_id --This was #var_Department_id in your query
)
VALUES (
#Employee_number,
#First_name,
#Last_name,
#Email,
#Research_area,
#Position_held,
#Highest_qualification,
#var_Department_id --This was #Department_name in your query
);";

Related

Stored procedure not working while calling in snowflake

Hope everyone is doing good.
I have started working on snowflake. I am trying to create a stored and procedure and calling this SP. Stored procedure is created without any issue. While calling it is saying that unexpected invalid token.
JavaScript compilation error: Uncaught Syntax issue: Invalid or unexpected token in USP_USERS at INSERT INTO stg.users_Temp position 0
CREATE OR REPLACE PROCEDURE ods.usp_Users()
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
var sql_command =
"INSERT INTO stg.users_Temp
SELECT
LTRIM(RTRIM(id)) AS Id
, LTRIM(RTRIM(name)) AS Name
, LTRIM(RTRIM(divisionId)) AS DivisionId
, LTRIM(RTRIM(divisionName)) AS DivisionName
, LTRIM(RTRIM(department)) AS Department
, LTRIM(RTRIM(email)) AS Email
, LTRIM(RTRIM(state)) AS State
, LTRIM(RTRIM(title)) AS Title
, LTRIM(RTRIM(username)) AS Username
, LTRIM(RTRIM(managerId)) AS ManagerId
, LTRIM(RTRIM(employeeId)) AS employeeId
, LTRIM(RTRIM(employeeType)) AS employeeType
, LTRIM(RTRIM(officialName)) AS officialName
, LTRIM(RTRIM(dateHire)) AS dateHire
, LTRIM(RTRIM(LocationId)) AS LocationId
FROM stg.users;
MERGE INTO
ods.Users AS t
USING
stg.users_Temp s
ON
(
s.Id = t.Id
)
WHEN
MATCHED
THEN
UPDATE
SET
t.Name = s.Name
,t.DivisionId = s.DivisionId
,t.DivisionName = s.DivisionName
,t.Department = s.Department
,t.Email = s.Email
,t.State = s.State
,t.Title = s.Title
,t.Username = s.Username
,t.LocationId = s.LocationId
,t.ManagerId = s.ManagerId
,t.employeeId = s.employeeId
,t.employeeType = s.employeeType
,t.officialName = s.officialName
,t.dateHire = s.dateHire
,t.EtlLastUpdatedDate = CURRENT_TIMESTAMP() :: TIMESTAMP
WHEN NOT MATCHED
THEN INSERT
(
id
,Name
,DivisionId
,DivisionName
,Department
,Email
,State
,Title
,Username
,LocationId
,ManagerId
,employeeId
,employeeType
,officialName
,dateHire
,CurrentRecord
,EtlCreatedDate
)
VALUES
(
s.id
,s.Name
,s.DivisionId
,s.DivisionName
,s.Department
,s.Email
,s.State
,s.Title
,s.Username
,s.LocationId
,s.ManagerId
,s.employeeId
,s.employeeType
,s.officialName
,s.dateHire
,'1'
,CURRENT_TIMESTAMP() :: TIMESTAMP
);"
try {
snowflake.execute (
{sqlText: sql_command}
);
return "Succeeded."; // Return a success/error indicator.
}
catch (err) {
return "Failed: " + err; // Return a success/error indicator.
}
TRUNCATE TABLE stg.users_Temp;
$$
;
//call ods.usp_Users();
While call SP it is throwing an error
Could someone help me on this issue.
Regards,
Khatija
You need to use the backtick (`) character to define multi-line strings:
CREATE OR REPLACE PROCEDURE ods.usp_Users()
RETURNS VARCHAR
LANGUAGE JAVASCRIPT
AS
$$
var sql_command =
`BEGIN
INSERT INTO stg.users_Temp
SELECT
LTRIM(RTRIM(id)) AS Id
, LTRIM(RTRIM(name)) AS Name
, LTRIM(RTRIM(divisionId)) AS DivisionId
, LTRIM(RTRIM(divisionName)) AS DivisionName
, LTRIM(RTRIM(department)) AS Department
, LTRIM(RTRIM(email)) AS Email
, LTRIM(RTRIM(state)) AS State
, LTRIM(RTRIM(title)) AS Title
, LTRIM(RTRIM(username)) AS Username
, LTRIM(RTRIM(managerId)) AS ManagerId
, LTRIM(RTRIM(employeeId)) AS employeeId
, LTRIM(RTRIM(employeeType)) AS employeeType
, LTRIM(RTRIM(officialName)) AS officialName
, LTRIM(RTRIM(dateHire)) AS dateHire
, LTRIM(RTRIM(LocationId)) AS LocationId
FROM stg.users;
MERGE INTO
ods.Users AS t
USING
stg.users_Temp s
ON
(
s.Id = t.Id
)
WHEN
MATCHED
THEN
UPDATE
SET
t.Name = s.Name
,t.DivisionId = s.DivisionId
,t.DivisionName = s.DivisionName
,t.Department = s.Department
,t.Email = s.Email
,t.State = s.State
,t.Title = s.Title
,t.Username = s.Username
,t.LocationId = s.LocationId
,t.ManagerId = s.ManagerId
,t.employeeId = s.employeeId
,t.employeeType = s.employeeType
,t.officialName = s.officialName
,t.dateHire = s.dateHire
,t.EtlLastUpdatedDate = CURRENT_TIMESTAMP() :: TIMESTAMP
WHEN NOT MATCHED
THEN INSERT
(
id
,Name
,DivisionId
,DivisionName
,Department
,Email
,State
,Title
,Username
,LocationId
,ManagerId
,employeeId
,employeeType
,officialName
,dateHire
,CurrentRecord
,EtlCreatedDate
)
VALUES
(
s.id
,s.Name
,s.DivisionId
,s.DivisionName
,s.Department
,s.Email
,s.State
,s.Title
,s.Username
,s.LocationId
,s.ManagerId
,s.employeeId
,s.employeeType
,s.officialName
,s.dateHire
,'1'
,CURRENT_TIMESTAMP() :: TIMESTAMP
);
END`
try {
snowflake.execute (
{sqlText: sql_command}
);
return "Succeeded."; // Return a success/error indicator.
}
catch (err) {
return "Failed: " + err; // Return a success/error indicator.
}
// TRUNCATE TABLE stg.users_Temp;
$$
;
PS: You can't user trancate as you tried to do, you should also call it using snowflake.execute. And when you run this proc, it would fail with "Failed: Multiple SQL statements in a single API call are not supported; use one API call per statement instead.". To overcome this issue, you can break up queries, and execute them separately or surround them in a BEGIN/END block.

How to select data from SQL Server stored procedure

I have a stored procedure as below
AS
BEGIN
IF(#statement = 1)
BEGIN
INSERT INTO [employee].[dbo].[emp_detail] ([fname], [lname], [age],[gender],
[department], [salary])
VALUES (#fname, #lname, #age, #gender,
#department, #salary)
END
IF(#statement = 2)
BEGIN
SELECT *
FROM emp_detail
END
I want to select data from the table by using this stored procedure.
My code is as below :
List<Nullable<int>> tbl = context.USP_MVC(2,fname, lname,Convert.ToInt32(age), gender, department, salary).ToList();
It is showing an error
int does not contain definition of to list
Create a complex type of stored procedure using .edmx file, and change the your like this:
List<StoredProcedureName_Result> tbl = context.USP_MVC(2, fname, lname, Convert.ToInt32(age), gender, department, salary).ToList();

Passing multiple params to stored procedure

I trigger stored procedure and pass parameters from Visual Studio to SQL Server stored procedure.
Here is code:
var cId = new SqlParameter("#clientId", clientId);
var result = _context.Database.SqlQuery<DamageEventsDTL>("SPDamageEventsDTL #clientId", cId );
But I need to pass multiple parameters (int, DateTime and list of integers).
Here how I do it:
int clientId = 5;
DateTime date = new DateTime("2016-07-01");
List<int> list= new List<int>(new int[] { 2, 3, 5 });
var cId = new SqlParameter("#clientId", clientId);
var dateEvents = new SqlParameter("#date", date);
var freqEvents = new SqlParameter("#list ", list );
var result = _context.Database.SqlQuery<DamageEventsDTL>("SPDamageEventsDTL #cId, #date, #list ", cId, dateEvents, list);
But it seems to be wrong way.
Any idea what I do wrong here?
you can also use an XML to send parameters to SQL, like this:
USE tempdb
GO
DECLARE #Element XML;
SET #Element='
<SavedOrderElement>
<Data>
<Age>5</Age>
<Nit>46546546546</Nit>
<Name>Jeff</Name>
<LastName>Thalliens</LastName>
<Email>VerizonBoughtYahoo#yahoo.com</Email>
<PokemonGo>Nothing</PokemonGo>
</Data>
</SavedOrderElement>' ;
;WITH ElementSavedOrders
AS
(
SELECT
CAST(c.query('data(Age)') AS VARCHAR(50)) as Age
,CAST(c.query('data(Nit)') AS VARCHAR(50)) as Nit
,CAST(c.query('data(Name)') AS VARCHAR(50)) as Name
,CAST(c.query('data(LastName)') AS VARCHAR(50)) as LastName
,CAST(c.query('data(Email)') AS VARCHAR(100)) as Email
,CAST(c.query('data(PokemonGo)') AS VARCHAR(100)) as PokemonGo
FROM #Element.nodes('SavedOrderElement/*') as T(c)
)
SELECT * FROM ElementSavedOrders

Stored procedure returns int value when the TSQL have full text search property

I have to use CONTAINS (full text search) in my stored procedure's query. So when I bind this stored procedure into my application through Entity Framework it returns an int value instead of a list of object.
EX:
Stored procedure:
ALTER PROCEDURE [dbo].[GetTableData]
(#UserId UNIQUEIDENTIFIER)
AS
BEGIN
SET NOCOUNT ON;
SELECT Column1, Column2
FROM TABLE1
WHERE Id = #UserId AND CONTAINS(Column1,'test')
END
Actual result:
public virtual int GetTableData(Nullable<System.Guid> userId)
{
var userIdParameter = userId.HasValue ?
new ObjectParameter("UserId", userId) :
new ObjectParameter("UserId", typeof(System.Guid));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<GetTableData_Result>("GetTableData", userIdParameter );
}
Expected result:
public virtual ObjectResult<GetTableData_Result> GetTableData(Nullable<System.Guid> userId)
{
var userIdParameter = userId.HasValue ?
new ObjectParameter("UserId", userId) :
new ObjectParameter("UserId", typeof(System.Guid));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<GetTableData_Result>("GetTableData", userIdParameter );
}
If I remove AND CONTAINS(Column1,'test') condition, it's working perfectly and gives the expected result.
I also tried with SET FMTONLY OFF options. That also not working.
How can I solve this problem?
Need to add any property or any other things in stored procedure?
Can anyone help me to solve this problem?
you need to create fulltext catalog on your table column.
here is reference.
https://msdn.microsoft.com/en-us/library/ms187787%28v=sql.110%29.aspx
Try this in your stored procedure:
SELECT Column1, Column2
FROM TABLE1 AS t1
WHERE Id = #UserId
AND EXISTS (SELECT
1 AS c1
FROM TABLE1 AS t2
WHERE (contains(t2.Column1,'test')) AND (t1.Id = t2.Id)
)

Using MyBatis to Insert into Sybase table with IDENTITY column as ID. How do I get ID returned?

I need to get the auto generated ID when doing the insert below. The insertRecord method returns the number of rows written. That is fine and expected. The Object Log, however, does not have it's id field updated to the auto generated ID. Any ideas?
CREATE TABLE LOG
(
ID NUMERIC(20,0) IDENTITY,
NAME VARCHAR(20) NOT NULL,
DESCRIPTION VARCHAR(200) NOT NULL,
USR VARCHAR(20) NOT NULL
)
public class Log
{
private long id;
private String name;
private String description;
private String user;
//getters+setters......
}
int insertRecord(#Param("log") Log log);
<insert id="insertRecord" parameterType="com.xxx.yyy.zzz.model.Log" useGeneratedKeys="true" keyProperty="id">
INSERT INTO LOG (NAME, DESCRIPTION, USR)
VALUES (#{log.name}, #{log.description}, #{log.user})
<selectKey keyProperty="id" resultType="long">
select ##identity
</selectKey>
</insert>
Got it.
The keyProperty in the select needed to be log.id. See below.
<selectKey keyProperty="log.id" resultType="long">
select ##identity AS id
</selectKey>

Resources