I'm studying a stored procedure with the following variable that I need to decipher, ResponseRange :
**#ResponseRange VARCHAR(64) = null,**
then later we have:
IF (#ResponseRange is not null)
BEGIN
INSERT
INTO #tempLK_ResponseStatuses
SELECT CONVERT(INT, val) FROM dbo.Split(#ResponseRange, ',')
END
IF (#ClientResponseRange is not null)
BEGIN
INSERT
INTO #tempClientLK_ResponseStatuses
SELECT CONVERT(INT, val) FROM dbo.Split(#ClientResponseRange, ',')
END
What is happening with the line
SELECT CONVERT(INT, val) FROM dbo.Split(....)
I believe all the above corresponds to the code from the Web-page CS file, of which here's a sample:
new ResponseGroup() {
ID = (int) ResponseStatusGroups.Completes,
Code = 1,
Label = "Completes",
ResponseCodes = null,
ClientResponseCodes = "10,11,12,13,14,15,16,17,18,19"
},
new ResponseGroup() {
ID = (int) ResponseStatusGroups.OverQuota,
Code = 2,
Label = "Over Quota",
ResponseCodes = "40,41,42,43,44,45,46,47,48,49",
ClientResponseCodes = "40,41,42,43,44,45,46,47,48,49"
Related
I am doing a procedure to loop over specific field names for 2 reasons:
I want to hash the field name itself using md5 (We are working with data vault);
I want to add each field name value as a row in the table.
I have the following procedure which is working perfect:
CREATE PROCEDURE ADD_OBSERVATION_VALUES()
RETURNS string
LANGUAGE JAVASCRIPT
EXECUTE AS CALLER
AS
$$
arr = [];
var row_num = 1;
// Set the indicators
COLUMN_FIELD_NAMES = ["care_beneficiary", "cg_child_6mo_receiv_ind_iycf_nbr_1st_cons_6mc_iycfc number",
"preg_women_rec_ind_counselling_nbr_1st_cons_pregw_iycfc",
...
];
COLUMN_FIELD_NAMES_TO_HASH = [
"cg_child_6mo_receiv_ind_iycf/nbr_1st_cons_6mc_iycfc",
"cg_child_6mo_receiv_ind_iycf/nbr_followup_2nd_time_6mc_iycfc",
...
];
try{
// while(rows_result.next()){
for (var col_num = 0; col_num<COLUMN_FIELD_NAMES_TO_HASH.length; col_num = col_num+1){
var COL_NAME = COLUMN_FIELD_NAMES_TO_HASH[col_num];
var query = "INSERT INTO LINK_OBSERVATION_FIELD SELECT (SELECT md5(concat(?, concat('CAMP', concat(CAMPNO, DATE))))), current_timestamp(), (SELECT 'ONA'), (SELECT (md5(concat(DATE, concat('CAMP', CAMPNO))))), md5(?) FROM IYCF_TEMP";
var stmt = snowflake.createStatement( {sqlText: query, binds:[COL_NAME, COL_NAME]} );
if(stmt.execute()){
// var query = "INSERT INTO SAT_FIELD_VALUES SELECT (SELECT (md5(md5(concat(?, concat('CAMP', concat(CAMPNO, DATE))))))), current_timestamp(), NULL, (SELECT 'ONA'), ?, (SELECT 'PENDING'), (SELECT _SUBMISSION_TIME), (SELECT md5(concat(?, concat('CAMP', concat(CAMPNO, DATE))))) FROM IYCF_TEMP";
// var stmt = snowflake.createStatement( {sqlText: query, binds: [COL_NAME, COL_NAME, COL_NAME] });
// stmt.execute()
}
}
// }
return "DONE"
}
catch(error){
return error
}
$$;
The first insert query is working fine, when it goes to the second insert query after successful execution, I get the following error:
Numeric value 'care_beneficiary' is not recognized
I am guessing that the error is coming from , ?, of the below insert query:
INSERT INTO SAT_FIELD_VALUES SELECT (SELECT (md5(md5(concat(?, concat('CAMP', concat(CAMPNO, DATE))))))), current_timestamp(), NULL, (SELECT 'ONA'), ?, (SELECT 'PENDING'), (SELECT _SUBMISSION_TIME), (SELECT md5(concat(?, concat('CAMP', concat(CAMPNO, DATE))))) FROM IYCF_TEMP;
The ? within the CONCATS are working fine, but the standalone field , ?, . In this standalone binded field, I want to get its value from the table not its name, and I am assuming that it is because the field is being read as with quotes, and the query is considering it string that should not be added to a numeric field.
Any idea how to remove quotes or let the query treat it as field name and not as a value?
The solution was as mentioned by Felipe in the comment section of the question, to bind and compose the query with strings and variables:
var query = "SELECT ... " + COL_NAME + "FROM ..."
Apparently IDENTIFIER(COL_NAME) didn't work for me but I am sure that it will work if I knew where to use the binding.
From the below source tutorials:
https://www.youtube.com/watch?v=Jt9vSY802mM
http://www.dotnetawesome.com/2017/07/curd-operation-on-fullcalendar-in-aspnet-mvc.html
How do I do the above code samples without Entity Framework, by just using SQL queries?
For example in the above source code, instead of
var v = dc.Events.Where(a => a.EventID == eventID).FirstOrDefault();
if (v != null)
{
dc.Events.Remove(v);
dc.SaveChanges();
status = true;
}
I want to do
DELETE FROM Even WHERE EventID = {0}
FirstOrDefault() in LINQ is equivalent to LIMIT 1 in MySQL, hence the LINQ function can be converted to SQL commands using IF or CASE WHEN like this (assumed commands are running inside a stored procedure):
DELIMITER //
-- 'Events' is a DbSet name by common convention,
-- therefore table name should be 'Event'
CREATE PROCEDURE procedure_name (IN eventID INT)
BEGIN
DECLARE v INT;
SET v = SELECT EventID FROM Event WHERE EventID = eventID LIMIT 1;
CASE WHEN v IS NOT NULL
THEN DELETE FROM Event WHERE EventID = v
ELSE -- do something else
END
-- alternative:
-- IF(v IS NOT NULL, DELETE FROM Event WHERE eventID = v, 0)
-- other stuff here
END//
DELIMITER ;
Note: If EventID is a primary key column, you can remove LIMIT 1 because query result only return single value.
Then, use CALL procedure_name(eventID) or include procedure_name in MySqlCommand to execute it.
Couple of ways:
using raw query in Entity Framework:
Open connection string via SqlConnection and execute:
Pseudo code for method 1:
string sqlDeleteStatement = "DELETE FROM Even WHERE EventID = #id";
List<SqlParameter> parameterList = new List<SqlParameter>();
parameterList.Add(new SqlParameter("#id", 1)); delete id = 1
_context.Database.SqlQuery(sqlDeleteStatement, parameterList);
Pseudo code for method 2:
using(SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Server=[server_name];Database=[database_name];Trusted_Connection=true";
string sqlDeleteStatement = "DELETE FROM Even WHERE EventID = #id";
SqlCommand command = new SqlCommand(sqlDeleteStatement , conn);
command.Parameters.Add(new SqlParameter("#id", 1)); //delete id = 1
command.ExecuteNonQuery();
}
I have a stored procedure for search screen where I have 5 different filters.
Users can leave the filters empty or have one filter and click on search button.
All the data is coming from database, I am trying to create stored procedure which can exclude columns in where clause if the parameter value is empty string.
#Id as nvarchar(256) = 1
#blnIsinProgress bit = 0
#strStatus varchar(20) = ''
#strName varchar(50) = ''
#strConfirmationNumber varchar(50) = 123
#dtmSubmittedFrom Date = '12/31/9999'
#dtmSubmittedTo Date = '12/31/9999'
as
BEGIN
SELECT *
FROM tblTable
WHERE
(#Id IS NULL OR lngID = #Id) AND
(#blnIsinProgress IS NULL OR blnIsinProgress = #blnIsinProgress) AND
(#strStatus = '' OR strStatus = #strStatus) AND
(#strName= '' OR strName= #strName) AND
(#strConfirmationNumber = '' or #strConfirmationNumber = #strConfirmationNumber )
End
But
Execute spManage 1,0,'','',123
will give me all the results
The problem is this line:
(#strConfirmationNumber = '' or #strConfirmationNumber = #strConfirmationNumber )
The second condition is always true. You have an extra #. So, try this:
(#strConfirmationNumber = '' or #strConfirmationNumber = strConfirmationNumber )
My views.py looks like following:
#api_view(('GET',))
def save_progress_for_particular_user(request, exerciseId, rating):
#view to call stored proc that stores the progress for a particular user
#save_progress(user_id,exercise_id,rating,date)
result=Exercise_progress_model.save_progress_for_particular_user(
request.user.id, exerciseId, rating, datetime.date.today())
serializer = ExerciseProgressSerializer(result, many=True)
return Response(serializer.data)
My models.py looks like following:
class Exercise_progress_model(models.Model):
# Model that will be rendered on the UI
#Field for storing intensity level
INTENSITY_LEVEL_CHOICES = (
(1, 'Really simple'),
(2, 'Rather Simple'),
(3, 'Simple'),
(4, 'Okay'),
(5, 'Difficult'),
(6, 'Rather Difficult'),
(7, 'Really Difficult'),
)
intensity_level = models.IntegerField(choices=INTENSITY_LEVEL_CHOICES)
#Field for storing progress
progress = models.IntegerField(default='0')
#Field for storing exercise type
EXERCISE_TYPE_CHOICES = (
(1, 'Best stretch'),
(2, 'Butterfly reverse'),
(3, 'Squat row'),
(4, 'Plank'),
(5, 'Push up'),
(6, 'Side plank'),
(7, 'Squat'),
)
exercise_id = models.IntegerField(choices=EXERCISE_TYPE_CHOICES)
#Field for storing current date
current_date = models.DateField()
#Field for storing user rating
user_rating = models.IntegerField(default='0')
# static method to save progress for a particular user
#staticmethod
def save_progress_for_particular_user(user_id, exercise_id, rating, date):
# create a cursor
cur = connection.cursor()
# execute the stored procedure passing in
# search_string as a parameter
cur.callproc('save_exercise_state', [user_id, exercise_id, rating, date,])
# grab the results
result = cur.fetchall()
cur.close()
User_progress_list = []
for row in result:
Epm = Exercise_progress_model()
Epm.intensity_level=row[0]
Epm.progress=row[1]
Epm.exercise_id=row[2]
Epm.user_rating=row[3]
Epm.current_date=row[4]
User_progress_list.append(Epm)
return User_progress_list
My serializers.py looks like following:
class ExerciseProgressSerializer(serializers.Serializer):
intensity_level = serializers.IntegerField(required=True)
progress = serializers.IntegerField(required=True)
exercise_type = serializers.IntegerField(required=True)
user_rating = serializers.IntegerField(required=True)
current_date = serializers.DateField()
My stored procedure looks like following:
delimiter //
CREATE PROCEDURE save_exercise_state(
p_user_id int, p_exercise_id int, p_rating int, p_date date
)
BEGIN
DECLARE lv_current_intensity, lv_progress, lv_final_intensity int;
DECLARE lv_date date;
select intensity_level into lv_current_intensity
from demo_exercise_state where
user_id=p_user_id and exercise_id=p_exercise_id;
select progress into lv_progress
from demo_exercise_state where
user_id=p_user_id and exercise_id=p_exercise_id;
select current_date into lv_date
from demo_exercise_state where
user_id=p_user_id and exercise_id=p_exercise_id;
select lv_progress, lv_current_intensity, lv_date;
If lv_date=p_date then
select "OK";
end if;
if p_rating=0 then
set lv_progress=lv_progress;
elseif p_rating=1 then
if lv_progress=3 then
set lv_progress=0;
if lv_current_intensity = 7 then
set lv_final_intensity = 7;
else
set lv_final_intensity = lv_current_intensity + 1;
end if;
else
if lv_current_intensity=7 then
set lv_progress=0;
set lv_final_intensity=lv_current_intensity;
else
set lv_progress=lv_progress+1;
set lv_final_intensity=lv_current_intensity;
end if;
end if;
elseif p_rating =-1 then
if lv_progress=0 then
if lv_current_intensity = 1 then
set lv_final_intensity = 1;
set lv_progress=0;
else
set lv_final_intensity = lv_current_intensity - 1;
set lv_progress=3;
end if;
else
set lv_progress=lv_progress-1;
set lv_final_intensity=lv_current_intensity;
end if;
end if;
Update demo_exercise_state
SET progress = lv_progress,
intensity_level = lv_final_intensity,
`current_date` = p_date,
user_rating = p_rating
WHERE user_id = p_user_id AND exercise_id = p_exercise_id;
SELECT intensity_level, progress, exercise_id, user_rating , current_date
FROM demo_exercise_state
WHERE user_id = p_user_id AND exercise_id = p_exercise_id AND user_rating=p_rating;
END
//
Screenshot of the result of executing this proc for
call save_exercise_state(4,1,1,curdate()); is as following
When I call this view I get tuple index out of range error for the line Epm.user_rating=row[3].
What is the reason for this? Is there any workaround?
Here is my stored Procedure
CREATE PROCEDURE `tblCarGarage_Insert`(
IN URL varchar(700),
IN Price int(7),
IN Make varchar(60),
IN Model varchar(60),
IN TrimLevel varchar(60),
IN Miles int(6),
IN ZipCode int(5),
IN Description varchar(80),
IN Color varchar(30),
IN Owner varchar(100),
IN VIN varchar(20),
IN VINKeyCode varchar(12),
IN CarYear int(4),
IN ListingID int(14))
INSERT INTO tblcargarage
SET URL = #URL,
Price = #Price,
rBit = b'1',
DateDiscovered = NOW(),
LastProcessDate = NOW(),
CarYear = #CarYear,
Make =
(SELECT uniqueID
FROM tbltranslationmake
WHERE make = 'Honda'),
Model =
(SELECT uniqueID
FROM tbltranslationmodel
WHERE model = #Model),
CarTrim =
(SELECT uniqueID
FROM tbltranslationtrim
WHERE trimlevel = #TrimLevel),
Miles = #Miles,
ZipCode = #ZipCode,
Description = #Description,
Color = #Color,
Owner = #Owner,
VIN = #VIN,
VINKeyCode = #VinkeyCode,
ListingID = #ListingID;
Here is my execution
SET #CarYear = '';
SET #URL = 'asdas';
SET #Price = 20112;
SET #Make = 'Honda';
SET #Model = 'Civic';
SET #TrimLevel = 'Ex';
SET #Miles = 20112;
SET #Description = 'asdasdasd';
SET #Color = 'yellow';
SET #Owner = 'asdasdas';
SET #VIN = 'qeqweqweqw2e';
SET #VinkeyCode = 'asd23sd';
SET #ListingID = 1231231;
SET #ZipCode = 12331;
CALL tblCarGarage_Insert(#CarYear,
#URL,
#Price,
#Make,
#Model,
#TrimLevel,
#Miles,
#Description,
#Color,
#Owner,
#VIN,
#VinkeyCode,
#ListingID,
#ZipCode)
SELECT uniqueID
FROM tbltranslationmake
WHERE make = 'Honda' returns 11 (as an int)
Model =
(SELECT uniqueID
FROM tbltranslationmodel
WHERE model = #Model),
Returns 712 as an int
CarTrim =
(SELECT uniqueID
FROM tbltranslationtrim
WHERE trimlevel = #TrimLevel),
returns 12334 as an int.
Yes all 3 of those columns are INT in my DB,
I keep getting 'Column 'Make' cannot be null, if i run the query as a non SP just as a query Insert into asd set x = 'x' ect... it works just fine with the same values. Any idea?
Thanks!
This must have to do something with passing in a varchar and the table expecting an int. Maybe it's not returning the correct error?
Looking at your code, the first problem I notice is that in your CALL statement you are passing the parameters in the wrong order. For example, in the stored procedure definition the first parameter is URL, but in your call to the procedure the first parameter you pass in is CarYear.
Try passing the parameters in the correct order and see if that works for you:
CALL tblCarGarage_Insert(
#URL,
#Price,
#Make,
#Model,
#TrimLevel,
#Miles,
#ZipCode,
#Description,
#Color,
#Owner,
#VIN,
#VinkeyCode,
#CarYear,
#ListingID
)