How to turn `''` into `Null` in PHP to send variables to the sql store procedure? - sql-server

I am using Laravel 5.2 and SQL Server. I have a store procedure for search customer. When I run with Null value it return 0 rows. It should be return all of the data.
This below is my code in my controller to run the store procedure:
$name = $request['name'];
$email = $request['email'];
$lower_age = $request['lower_age'];
$upper_age = $request['upper_age'];
$gender = $request['gender'];
$maritalstatus = $request['maritalstatus'];
$search = DB::select("EXEC dbo.search '".$name."',
'".$email."',
'".$lower_age."',
'".$upper_age."',
'".$gender."',
'".$maritalstatus."'"
);
This is when I print_r my store procedure:
EXEC dbo.search '', '', '', '', '', ''
I need '' become NULL like this below:
EXEC dbo.search NULL, NULL, NULL, NULL, NULL, NULL
Do you know how?

".($lower_age === '' ? 'null' : "'$lower_age'").",

Related

EF Core 3.1 - Database scalar function - string.Join

Since string.Join(...) is not translatable in the latest EF Core and a lot of our queries do use that method, I'm currently trying to implement it with user-defined functions. I can see that the function actually works in the ssms but I can't get it to work in c#.
The method needs to accept an array of strings as an input so I created a user-defined table type:
IF TYPE_ID('[system].[stringList]') IS NULL
BEGIN
CREATE TYPE system.stringList AS TABLE (val nvarchar(max))
END
GO
Then I created the function itself:
create function toCommaSeparatedString(#strings [system].[stringList] readonly)
returns nvarchar(max)
as
begin
DECLARE #values nvarchar(max)
SELECT #values = COALESCE(#values + ', ', '') + [val]
FROM #strings
return #values
end
I can verify that it works by simply executing the following sql in the ssms:
declare #input [system].[stringList]
insert into #input values ('1'), ('2'), ('3'), ('4')
select dbo.toCommaSeparatedString(#input)
In c# I declared the function on my DbContext (I tried both string[] and IEnumerable<string>):
[DbFunction("toCommaSeparatedString", "dbo")]
public static string ToCommaSeparatedString(string[] strings) => throw new NotImplementedException();
And used it:
...
var output = MyDbContext.ToCommaSeparatedString(new [] { "1", "2" });
...
but I'm getting an exception:
"The parameter 'strings' for the DbFunction 'BusinessUnitDbContext.ToCommaSeparatedString' has an invalid type 'string[]'. Ensure the parameter type can be mapped by the current provider.",
Is it possible to achieve what I'm trying to achieve here? Should I also configure that function on the DbContext?
EDIT:
Here is my custom projection that i want to use to create the viewmodel:
private static IQueryable<IView> ProjectToJobOverView(this IQueryable<Job> entities)
{
return entities.Select(j => new JobOverView
{
Id = j.EntityId,
Deleted = j.Deleted.HasValue,
Name = j.Name,
Status = j.Status.ToString(),
NumberOfInstructionSets = j.Tasks.Count(t => t.InstructionSet != null),
NumberOfCompletedInstructionSets = j.Tasks.Count(t => t.InstructionSet.IsCompleted),
NumberOfOrderLines = j.Tasks
.SelectMany(t => t.TaskOrderLines).Select(x => x.OrderLineId)
.Distinct()
.Count(),
Details = j.Tasks
.OfType<StockMovementTask>()
.Where(t => t.InstructionSet != null)
.Select(t => t.InstructionSet)
.Select(s => new JobOverviewDetail
{
Id = s.EntityId,
Deleted = s.Deleted.HasValue,
State = s.Tasks.First().OperationState.ToString(),
DeliveryMethod = BusinessUnitDbContext.ToCommaSeparatedString(
s.Tasks
.First()
.TaskOrderLines.Where(x => x.OrderLine.Order is OutgoingOrder && (x.OrderLine.Order as OutgoingOrder).DeliveryType != null)
.Select(x => (x.OrderLine.Order as OutgoingOrder).DeliveryType.Name).ToArray()),
}),
Categories = j.Tasks.Select(t => t.Process.ProcessDefinition.ProcessDefinitionGroup.ProcessDefinitionCategory.ToString()).Distinct().ToArray(),
OrderNumbers = j.Tasks.OfType<StockMovementTask>().SelectMany(t => t.TaskOrderLines).Select(j => j.OrderLine.Order.Number).Distinct().ToArray(),
});
}

T-SQL passing URL as parameter is not working in stored procedure

I have 2 scenarios below where one case is working and another case is not I am not sure what is wrong.
Not working case which I want to implement :
exec[dbo].[test]
#Alias = 'test',
#Pipeline = 'testing_',
#SBU = 'Test',
#LoB = ' Test',
#SupportChannel = 'Test',
#Detail = 'testing personal version',
#Status = 0,
#Error = ' no error',
#Debug = 1
DECLARE #ReportURL NVARCHAR(MAX)
IF #Pipeline = 'testing_'
SET #ReportURL = N'https://powerbi.microsoft.com/en-us/'
IF #Pipeline = 'testing1_'
SET #ReportURL = N'https://www.microsoft.com/en-us/'
DECLARE #SuccessFooter NVARCHAR(MAX) = 'results can be found </br></br>' +
'<p> Click here to view reports.</p>'
2nd the same case where I am passing the URL directly which I do not want to do as I have multiple links to pass to that parameter.
exec[dbo].[test]
#Alias = 'test',
#Pipeline = 'testing_',
#SBU = 'Test',
#LoB = ' Test',
#SupportChannel = 'Test',
#Detail = 'testing personal version',
#Status = 0,
#Error = ' no error',
#Debug = 1
DECLARE #ReportURL NVARCHAR(MAX)
IF #Pipeline = 'testing_'
SET #ReportURL = N'https://powerbi.microsoft.com/en-us/'
IF #Pipeline = 'testing1_'
SET #ReportURL = N'https://www.microsoft.com/en-us/'
DECLARE #SuccessFooter NVARCHAR(MAX) = 'results can be found </br></br>' +
'<p> Click here to view reports.</p>'
Does anyone know how to solve the problem?
I want to pass the link dynamically. If I pass testing_ it should take 1st link and if I pass testing1_ it should take 2nd link.
When I execute [dbo].[test], this will send me an email and the link for the corresponding website

Snowflake : Load JSON with null values using empty string

I want to load empty strings in JSON as null value into snowflake table.
The snowflake document says that this should be possible with NULL_IF=('')
I tried that in COPY INTO statement, but did not work as expected.
Here is my sample JSON:
{
"Id": 100,
"Address": ""
}
Here is my sample query:
COPY INTO my_table FROM 's3://my_bucket/'
FILES = ('my_file.json')
FILE_FORMAT = (TYPE = json STRIP_OUTER_ARRAY = true NULL_IF = ('\\N', 'NULL', 'null', 'NUL', ''))
CREDENTIALS = (AWS_KEY_ID = 'my_key' AWS_SECRET_KEY = 'my_secret_key')
MATCH_BY_COLUMN_NAME = CASE_SENSITIVE
ON_ERROR = 'CONTINUE'
FORCE = TRUE ;

how to insert form data into database in moodle

I have created a simple form in the NEWMODULE plugin and a database table to save form data, but i don't know how to insert the form data into the database. I save the code into my_form.php, this is my code:
class myform_form extends moodleform {
public function definition() {
global $DB,$CFG;
$mform = &$this->_form;
$mform->addElement('text', 'tendethi', get_string('tendethi', 'myform'));
$mform->setType('tendethi', PARAM_TEXT);
$mform->setDefault('tendethi','Nhập tên đề thi');
$mform->addElement('text', 'mdt', get_string('madethi','myform'));
$mform->setType('mdt', PARAM_TEXT);
$mform->setDefault('mdt','Nhập mã đề thi');
$mform->addElement('duration', 'timelimit', get_string('thoigianlambai','myform'));
$mform->setType('timelimit', PARAM_TEXT);
$mform->addElement('text', 'gvrd', get_string('giaovienrade','myform'));
$mform->setType('gvrd', PARAM_TEXT);
$mform->setDefault('gvrd','Nhập họ tên giáo viên ra đề thi');
$mform->addElement('text', 'tmh', get_string('tenmonhoc','myform'));
$mform->setType('tmh', PARAM_TEXT);
$mform->setDefault('tmh','Nhập tên môn học');
$buttonarray=array();
$buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
$buttonarray[] = &$mform->createElement('reset', 'resetbutton', get_string('revert'));
$buttonarray[] = &$mform->createElement('cancel');
$mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
$mform->closeHeaderBefore('buttonar');
and this is code insert form data into database :
// insert database into table
//global $DB;
$tendethi = optional_param('tendethi', null, PARAM_TEXT);
$mdt = optional_param('mdt', null, PARAM_INT);
$timelimit = optional_param('timelimit', null, PARAM_INT);
$gvrd = optional_param('gvrd', null, PARAM_TEXT);
$tmh = optional_param('tmh', null, PARAM_TEXT);
if($data = $mform->get_data()){
$record = new stdClass();
$record->tendethi = $tendethi ;
$record->mdt = $mdt ;
$record->timelimit = $timelimit ;
$record->gvrd = $gvrd ;
$record->tmh = $tmh ;
$DB=insert_record('myform_form', $record, false);
}
please help me !
Your code should look roughly like this:
$urlaftersubmission = new moodle_url(); // You will need to fill this in.
$form = new myform_form();
if ($form->is_cancelled()) {
redirect($urlaftersubmission);
}
if ($data = $form->get_data()) {
$DB->insert_record('name_of_table', $data);
redirect($urlaftersubmission);
}
echo $OUTPUT->header();
$form->display();
echo $OUTPUT->footer();
Note, you may have to adjust the data slightly for it to be in the correct format for inserting in the database. You should also make sure that you create your database table using the install.xml or upgrade.php files in your plugin (and use the Moodle built-in xmldb editor to generate those files correctly), otherwise Moodle will not recognise them for inserting data.

Django - specify column order on dynamic model

Say we create a Model like this:
def model_factory(*args, **kwargs):
attrs = {}
attrs['Meta'] = type('Meta', (object,), {
'verbose_name': 'My Dynamic model',
'db_table': 'dynamic_model_table'
})
# Ex. add an arbitrary fields
attrs['username'] = models.CharField(
max_length = 128,
db_column = 'username'
)
attrs['email'] = models.CharField(
max_length = 128,
db_column = 'email'
)
return type('DynamicModel', (models.Model,), attrs)
How do I specify the column order in the database? I.e the CREATE statement must be
CREATE TABLE "dynamic_model_table" (
"username" varchar(128) NOT NULL,
"email" varchar(128) NOT NULL
)
Using the code example however, the column order will be random.

Resources