Error:insert hierarchy values using storedprocedure - sql-server-2008

I'm getting this error when trying to run a query that inserts results into a table in sql.
im passing the table name as parameter,how to give the hierarchy value to the insert statement.
here is my code:
declare #pathhere hierarchyid
select #pathhere=Path from SectionDetails where Sectionid=#sectionid and SectionName=#sectionname and Batchid=#batchid and Deptid=#deptid and Schoolid=#schoolid
insert stmt:
set #sqlstmt = 'insert into '+#batch+'(StudentID, StudentName,SectionID,SectionName,BatchID,BatchName, DeptID,DeptName, SchoolID,Path)
values('''+#sectionid+''','''+#sectionname+''','''+#sectionid+''','''+#sectionname+''','''+#batchid+''','''+#batchname+''','''+ #deptid+''','''+#deptname+''', '''+#schoolid+''','+ CAST(#pathhere as hierarchyid)+')'
exec(#sqlstmt)
im getting error in this line:
'+ CAST(#pathhere as hierarchyid)+'
as Invalid operator for data type. Operator equals add, type equals hierarchyid.
can anyone pls help me out how to pass the hierarchy value

You're trying to create a string that can be executed as a statement. So you need to get your hierarchyid into nvarchar(max) instead.
try: #pathhere.ToString()

Related

Sql Error: Operand should contain 1column(s)

I'm trying to create a SQL function which is collecting JSON data from the db . First i faced the problem that i cant write function(JSON_EXTRACT,...) but after little research i think when i remove the "function" it works . But now when i try to put the values to List it throws this error .
My Function :
create function returnRecord()
returns boolean
deterministic
begin
declare #myList varchar(255);
SELECT r.data as r1
INTO #myList
FROM records r
join columns c on r.view_id = c.view_id
where ('JSON_EXTRACT', r.data, c.name);
end;
I was trying different ways and i want to take the Json data from the db .

hsqldb procedure with date Input parameter

I need to write a test for some download operation. This operation call procedure from MSSQL database, take result set and java make some stuf. For test I use hsqldb.
My procedure:
CREATE PROCEDURE map.Get1(IN packageName varchar(100),
IN downloadDate DATE)
READS SQL DATA DYNAMIC RESULT SETS 1 BEGIN ATOMIC
DECLARE result CURSOR WITH RETURN FOR SELECT * FROM map.tvschedule FOR READ ONLY;
OPEN result;
END
This procedure wan't work, i have an exception
call map.GET1('Genre','2018-03-10');
[42561][-5561] incompatible data type in conversion
java.lang.RuntimeException: org.hsqldb.HsqlException: incompatible data type
in conversion
But this(without date parameter) work well:
CREATE PROCEDURE map.Get1(IN packageName varchar(100))
READS SQL DATA DYNAMIC RESULT SETS 1 BEGIN ATOMIC
DECLARE result CURSOR WITH RETURN FOR SELECT * FROM map.tvschedule FOR READ ONLY;
OPEN result;
END
call map.GET1('Genre');
first needed row
second needed row
I am not going to use input parameter, but i need this procedure to be looking i am going to.
My question is How to use date input parameter with hsqldb procedures?
UPDATE1:
I used TO_DATE and now it works well, but i have no data in my result set, my java code is:
try (CallableStatement callableStatement = connection.prepareCall("{ call
map.GetGenreProtocol( ?, ? ) }")) {
callableStatement.setString(1, packageName);
callableStatement.setDate(2, date);
callableStatement.execute();
ResultSet resultSet = callableStatement.getResultSet();
while (resultSet.next()) {
Interval Interval = new Interval();
Interval.setDuration(resultSet.getInt("duration"));
Interval.setMappingTargetId(resultSet.getInt("mappingTargetId"));
Interval.setGenreId(resultSet.getInt("genreId"));
Interval.setStart(resultSet.getLong("start"));
Interval.setCategoryId(resultSet.getInt("categoryId"));
Interval.setCategoryName(resultSet.getString("categoryName"));
Interval.setGenreName(resultSet.getString("genreName"));
Interval.setDescription(resultSet.getString("description"));
Intervals.add(Interval);
}
}
Use the TO_DATE function.
For example:
call map.GET1('Genre', TO_DATE('2018-03-10', 'YYYY-MM-DD'));
I guess you need to create a function that returns a table instead of a procedure:
CREATE FUNCTION map.Get1(IN packageName VARCHAR(100),
IN downloadDate DATE)
RETURNS TABLE(.....)
READS SQL DATA
BEGIN ATOMIC
....
END;

Updating integer column from jsonb member fails with: column is of type integer but expression is of type jsonb

In a PostgreSQL 9.5 table I have an integer column social.
When I try to update it in a stored procedure given the following JSON data (an array with 2 objects, each having a "social" key) in the in_users variable of type jsonb:
'[{"sid":"12345284239407942","auth":"ddddc1808197a1161bc22dc307accccc",**"social":3**,"given":"Alexander1","family":"Farber","photo":"https:\/\/graph.facebook.com\/1015428423940942\/picture?type=large","place":"Bochum,
Germany","female":0,"stamp":1450102770},
{"sid":"54321284239407942","auth":"ddddc1808197a1161bc22dc307abbbbb",**"social":4**,"given":"Alxander2","family":"Farber","photo":null,"place":"Bochum,
Germany","female":0,"stamp":1450102800}]'::jsonb
Then the following code is failing:
FOR t IN SELECT * FROM JSONB_ARRAY_ELEMENTS(in_users)
LOOP
UPDATE words_social SET
social = t->'social',
WHERE sid = t->>'sid';
END LOOP;
with the error message:
ERROR: column "social" is of type integer but expression is of type jsonb
LINE 3: social = t->'social',
^
HINT: You will need to rewrite or cast the expression.
I have tried changing that line to:
social = t->'social'::int,
but then I get the error:
ERROR: invalid input syntax for integer: "social"
LINE 3: social = t->'social'::int,
^
Why doesn't PostgreSQL recognize that the data is integer?
From the JSON-TYPE-MAPPING-TABLE I was having the impression that JSON number would be auto-converted to PostgreSQL numeric type.
A single set-based SQL command is far more efficient than looping:
UPDATE words_social w
SET social = (iu->>'social')::int
FROM JSONB_ARRAY_ELEMENTS(in_users) iu -- in_user = function variable
WHERE w.sid = iu->>'sid'; -- type of sid?
To answer your original question:
Why doesn't PostgreSQL recognize that the data is integer?
Because you were trying to convert the jsonb value to integer. In your solution you already found that you need the ->> operator instead of -> to extract text, which can be cast to integer.
Your second attempt added a second error:
t->'social'::int
In addition to the above: operator precedence. The cast operator :: binds stronger than the json operator ->. Like you found yourself already, you really want:
(t->>'social')::int
Very similar case on dba.SE:
Querying JSONB in PostgreSQL
I've ended up using:
FOR t IN SELECT * FROM JSONB_ARRAY_ELEMENTS(in_users)
LOOP
UPDATE words_social SET
social = (t->>'social')::int
WHERE sid = t->>'sid';
IF NOT FOUND THEN
INSERT INTO words_social (social)
VALUES ((t->>'social')::int);
END IF;
END LOOP;

Stored Procedure for multiple value with single parameter in SQL Server

I have this form in C# with a listbox where I selected 4 items. Now I want to make single stored procedure using which I can find data from single table for all this selected item with single parameter.
As I am a beginner when it comes to SQL Server, I completely don't know this type of procedure
Thanks, but this is not my question's answer
I want a Single Stored Procedure for all Items which are selected in ListBox
Create Procedure procedureName
(
#ItemName varchar(50),
)
AS
BEGIN
(
Select * from item_master where item_name = #ItemName
)
END
by this Query i can find data for one ItemName, but i want for all selected Items in Listbox, even I don't know the C# code also,
so plz help me....
This is a very simple example that does what you want. You would not want to use hard-coded connection strings, especially in-line, and you would want error-handling, but I am going for as much clarity as possible. You would also probably want to make the column length greater than 50 characters, but I made it match your column definition.
Also, I would recommend a generic approach, passing keys (column names) and values, so as to be able to use it for any sort of criteria, but you asked that I keep it to exactly what you require, so I trimmed it down to the essential.
This example returns all the Employees with FirstName matching any in the list passed to the stored procedure (as a user-defined table type).
First, create a user-defined table type (to hold the values you want to pass to the stored procedure) in your SQL Server database as follows:
CREATE TYPE [dbo].[FilterValues] AS TABLE(
[Value] [varchar](50) NOT NULL,
PRIMARY KEY CLUSTERED
(
[Value] ASC
)
)
The stored procedure to return the Employees looks as follows (note that it has the user-defined table type as the type of the single parameter passed in):
CREATE PROCEDURE [dbo].[GetEmployees] (
#FirstNameFilterValues dbo.FilterValues READONLY
)
AS
BEGIN
SELECT * FROM Employees
INNER JOIN #FirstNameFilterValues fv ON fv.Value = Employees.FirstName;
END
That's the SQL Server side done. To call it from C#, you can create a DataTable with a single column matching the column name and populate it with the values you want. In this simple example, I populate it with two names, but it could be as many as you want.
var filterValuesDataTable = new DataTable();
filterValuesDataTable.Columns.Add(new DataColumn("Value", typeof(string)) { AllowDBNull = false });
filterValuesDataTable.Rows.Add("Frodo");
filterValuesDataTable.Rows.Add("Sam");
using (var connection = new SqlConnection("server=.;Initial Catalog=Test;Integrated Security=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "GetEmployees";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#FirstNameFilterValues", filterValuesDataTable);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1}", reader["FirstName"], reader["LastName"]);
}
reader.Close();
}
}
connection.Close();
}

JPA passing parameter as Set

i want to pass a parameter in the jpql as set in an update statement. here is the statement:
Query query = entityManager.createQuery("UPDATE Patient patient SET "
+"patient.surname=:surname, "
+"patient.firstname=:firstname, "
+"patient.homeAddress=:homeAddress, "
+"patient.relatedPersons=:relatedPersons, "
+"patient.hospital=:hospital "
+"WHERE patient.id=:id");
query.setParameter("surname", updatablePatient.getSurname());
query.setParameter("firstname", updatablePatient.getFirstname());
query.setParameter("homeAddress", updatablePatient.getHomeAddress());
query.setParameter("relatedPersons", updatablePatient.getRelatedPersons());
query.setParameter("hospital", updatablePatient.getHospital());
query.setParameter("id", id);
but i get the following error:
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [****] was not matching type [java.util.Set]; nested exception is java.lang.IllegalArgumentException: Parameter value [****] was not matching type [java.util.Set]
any help would be really appreciated.
thanks in advance
Update statements in JPQL are rarely used, and should be used for batch updates, but not simply to update one entity. They translate directly to SQL, and you can't update a patient and all his related persons like this in SQL. The same goes for JPQL.
To do what you want to do, just get the patient from the database, and set the new properties into the loaded patient :
Patient p = (Patient) entityManager.find(Patient.class, id);
p.setSurname(updatablePatient.getSurname());
p.setRelatedPersons(updatablePatient.getRelatedPersons());
// ... set other properties
Or, if the updatable patient is a detached copy of the patient to update, and thus has the same ID,
Patient p = (Patient) entityManager.merge(updatablePatient);
The whole point of JPA (or at least one of its points) is to be able to use and modify an object graph rather than use queries to create and update data in database.
There is no support for updating set (or in general any collection valued field) via JPQL. In JPA 2.0 specification this is spelled as follows:
update_clause ::= UPDATE entity_name [[AS] identification_variable]
SET update_item {, update_item}*
update_item ::= [identification_variable.]
{state_field | single_valued_object_field} = new_value
For more details: JPQL BNF