I want to insert those values also which have version null and and for version null I don't have status.
I am getting all data from datatable to procedure table type and then how do I check that the incoming data has version null or not?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[uspInsertFilterData]
#sqlDataTable SqlTableType READONLY
AS
BEGIN
IF (#sqlDataTable.Version IS NOT NULL OR #sqlDataTable.Version != '')
BEGIN
INSERT INTO FilterCombination (Version, HotFix, Resourcetype, Language)
(SELECT
t1.Product, t1.Version, t1.HotFix, t1.Resourcetype,
t1.Language
FROM
#sqlDataTable t1, Product_Version_Mapping t2
WHERE
t1.Product = t2.Product
AND t1.Version = t2.Version
AND t2.Status = 'Correct')
END
ELSE
BEGIN
INSERT INTO FilterCombination (Product, Version, HotFix, Resourcetype, Language)
(SELECT
t1.Product, t1.Version, t1.HotFix, t1.Resourcetype, t1.Language
FROM
#sqlDataTable t1, Product_Version_Mapping t2
WHERE
t1.Product = t2.Product);
END
END
This query is not working. Please help
For checking null values, you can use NULLIF like so...
IF NULLIF(#PreviousStartDate, '') IS NULL
Please refer below link.
Check if a parameter is null or empty in a stored procedure
Related
i want to get count of no.of rows present in table which i pass at runtime to a function.
i have created a procedure and function to execute dynamic queries. function will not allow dynamic query because i am calling procedure from function.
that procedure having dynamic query.
///////procedure///////
CREATE PROCEDURE bizopsgolddev.`test1`(tbnm varchar(100))
begin
declare sql_text varchar(200);
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SELECT CONCAT(sql_text, ' is not valid');
END;
set sql_text=concat('select count(*) from ',tbnm);
SET #SQL := sql_text;
PREPARE stmt FROM #SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
end;
//////function//////
DROP FUNCTION IF EXISTS xyz;
CREATE FUNCTION `xyz`(tname varchar(100)) RETURNS int(11)
begin
declare val int;
call test1(tname);
return 1;
end;
if i execute this //select xyz('axpdc')// it should return rows count
can any one tell me how can i get count by passing table name to function(in mariadb only)
As I understand the question, the solution would be a function that returns the row count of a table with it's name passed to the function as a parameter.
I think this could be done by querying the information_schema database in MariaDB. A function could look like this:
CREATE DEFINER = 'yourUsername'#'192.168.%'
FUNCTION testDataBase.fn_GetRowCount(tableName VARCHAR(128))
RETURNS int(11)
BEGIN
-- This could be a parameter if need it to be.
DECLARE databaseName varchar(40) DEFAULT 'testDataBase';
DECLARE result int DEFAULT -1;
SELECT t.TABLE_ROWS INTO result
FROM information_schema.TABLES t
WHERE t.TABLE_NAME = tableName
AND t.TABLE_SCHEMA = databaseName;
RETURN result;
END
In order for this to work the user mentioned as the definer must have read privilege to the TABLES table in the information_schema database, otherwise you might get an error (tbh, I don't know if this is necessary).
There is a lot of useful information to be grabbed from the information_schema database.
I am using Merge Statement in my SSIS package. The problem is that it doesn't update the datetime column when i run the package. It inserts the datetime correctly but doesn't update them from NULL to some datetime if a new datetime is available in source database.
Both source and destination has same column type (datetime(2),null).
I am using the code below in SQL Task after truncating staging table.
MERGE abc.dbo.invoices AS targe
USING (SELECT
ID
,cash_received_date
,schedule_datetime
,delivery_date
FROM Staging.dbo.tmpabcinvoices) AS sourc
ON targe.id = sourc.id
WHEN MATCHED and
targe.schedule_datetime <> sourc.schedule_datetime
or
targe.delivery_date <> sourc.delivery_date
or
targe.cash_received_date <> sourc.cash_received_date
THEN UPDATE SET
,targe.schedule_datetime=sourc.schedule_datetime
,targe.delivery_date=sourc.delivery_date
,targe.cash_received_date=sourc.cash_received_date
WHEN NOT MATCHED THEN
INSERT(
old_invoiceid
,cash_received_date
,schedule_datetime
,delivery_date
)
VALUES
(
sourc.old_invoiceid
,sourc.cash_received_date
,sourc.schedule_datetime
,sourc.delivery_date
);
GO
You have a comma which shouldn't be there at the start of this line:
,targe.schedule_datetime=sourc.schedule_datetime
Also, you'll need to add this to take care of the NULLs:
targe.schedule_datetime <> sourc.schedule_datetime
or (targe.schedule_datetime IS NULL AND sourc.schedule_datetime IS NOT NULL)
or targe.delivery_date <> sourc.delivery_date
or (targe.delivery_date IS NULL AND sourc.delivery_date IS NOT NULL)
or targe.cash_received_date <> sourc.cash_received_date
or (targe.cash_received_date IS NULL AND sourc.cash_received_date IS NOT NULL)
While ANSI_NULLS is set to ON, NULLs are basically unknowns, so they can't be evaluated to either 'equal to' or 'not equal to'.
Thanks in advance for anyone's help. This is mystery which is driving me crazyyyy :(.
IF I run this following stored procedure directly on SQL server 2008R2, it returns the desired rows. But if I call this via ASP.net(3.5) it returns empty data from the last Select statement in SP.
Is there any scoping involved in this regarding the temp table #_CalendarDate?
Stored Procedure:
USE[DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [WC].[spsGetDayCyclePeriod]
(
#Param_StartDate datetime,
#NumberOfDayRange int,
#Campus_Type varchar(2)
)
AS
DECLARE #DateRangeStart datetime
DECLARE #DateRangeEnd datetime
DECLARE #_CalendarDate TABLE (CollegeDate datetime)
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SET DATEFIRST 1
SELECT #DateRangeStart=max(CalendarDate) FROM [X].dbo.CalendarEvents
WHERE CalendarDate <= #Param_StartDate and left(CalendarType,1)= #Campus_Type
and (CalendarType <> #Campus_Type+'_H' and CalendarType<>'H'
and convert(INT, right(CalendarType, len(CalendarType)-3))>0)
SELECT #DateRangeEnd=min(CalendarDate) FROM [X].dbo.CalendarEvents
WHERE CalendarDate >= dateadd(day, #NumberOfDayRange-1, #Param_StartDate)
and left(CalendarType,1)= #Campus_Type and (CalendarType <> #Campus_Type+'_H'
and CalendarType<>'H' and convert(INT, right(CalendarType, len(CalendarType)-3))=0)
--Get all Dates within range
;WITH CollegeDate AS
(
SELECT #DateRangeStart AS DateValue
union all
SELECT dateadd(day, 1, DateValue)
FROM CollegeDate
WHERE dateadd(day, 1, DateValue) <= #DateRangeEnd
)
INSERT INTO #_CalendarDate (CollegeDate)
SELECT DateValue FROM CollegeDate OPTION (MAXRECURSION 0)
SELECT * from #_CalendarDate
END
ASP.Net code:
DataTable dayCycle = new DataTable();
var dateTimestr = startDate.ToString("yyyy-MM-dd HH:mm:ss");
using (SqlCommand sqlCommand = new SqlCommand("WC.spsGetDayCyclePeriod", new SqlConnection(Connection)))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
var range = endDate.Subtract(startDate).Days;
sqlCommand.Parameters.Add(new SqlParameter("#Param_StartDate", dateTimestr));
sqlCommand.Parameters.Add(new SqlParameter("#NumberOfDayRange", range));
sqlCommand.Parameters.Add(new SqlParameter("#Campus_Type", campus));
//dayCycle = SqlHelper.GetDataTableUsingSqlCommand(sqlCommand);
try
{
SqlDataAdapter _dap = new SqlDataAdapter(sqlCommand);
_dap.Fill(dayCycle);
}
catch (Exception ex)
{ throw new Exception(ex.ToString()); }
return dayCycle;
Pass #Param_StartDate as a date time object rather than a string.
Thanks everyone for help.
Solved the problem myself ! Hopefully it will help someone else as well in future. Here is the answer:
In above ASP.net code:
sqlCommand.Parameters.Add(new SqlParameter("#Campus_Type", campus));
campus is a enum type and when I was calling the above method with enum type I was actually passing the int value instead of string. So this is what I change to. This was confusing because when I was debugging my code I was using cursor on top of the #campus which basically calls toString so I was seeing the right value (which was wrong) the actual value was passed was number of enum.
sqlCommand.Parameters.Add(new SqlParameter("#Campus_Type", campus.ToString()));
And the above change solved the problem.
What I learned from this is Always...Always confirm that the arguments you intend to pass to SP is what SP is receiving so retrieve back your passed arguments by running the following before you do anything with Stored procedures...
Select #Your_Param1, #Your_Param2
And then check on code side that you are receiving what you are expecting.
In my project EF calls a stored procedure which is shown below. It returns either 1 or scope identity.
On EF function imports, the stored procedure is listed with a return type of decimal.
When the stored procedure returns scope identity, everything is ok.
But when if condition of sp satisfies, ef throws error as
The data reader returned by the store data provider does not have enough columns for the query requested.
Pls help..
This is my stored procedure:
#VendorId int,
#ueeareaCode varchar(3),
#TuPrfxNo varchar(3),
#jeeSfxNo varchar(4),
#Tjode varchar(3),
#uxNo varchar(3),
#TyufxNo varchar(4),
#Iyuy bit
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
SET NOCOUNT ON;
IF EXISTS (Select dfen_id
from dbo.efe_phfedwn_eflwn
where
[yu] = #Tyuode and
[uy] = #TuyxNo and
[yuno] = #Tuo)
return 1
ELSE
Begin
INSERT INTO dbo.yu
....................
Select Scope_Identity()
End
END
The error tells us that EF is expecting a result set and when we use RETURN we don't get a result set. Your error means that the stored procedure is returning an integer but EF is expecting a decimal, so we just CAST the selected values to a decimal.
So modify the SQL so that we SELECT instead of RETURN, like so (not forgetting to use CAST):
IF EXISTS (Select cntct_ctr_phn_ln_id
from dbo.cntct_ctr_phn_ln
where
[toll_free_phn_area_cd] = #TollfreeareaCode and
[toll_free_phn_prfx_no] = #TollfreePrfxNo and
[toll_free_phn_sfx_no] = #TollfreeSfxNo)
SELECT CAST(1 AS decimal)
Then also CAST the result of SCOPE_IDENTITY() to a decimal:
SELECT CAST(SCOPE_IDENTITY() AS decimal)
I have a stored procedure which inserts records into a table using values from my table variable. (The table variable is sent to SQL from ASP.NET) It works perfect and looks like this...
CREATE PROCEDURE sp_SaveResponses
(
#TableVariable SaveResponsesTableType READONLY
)
AS
BEGIN
INSERT INTO tbl_Responses
(
assessmentid, questionid, answerid
)
SELECT assessmentid, questionid, answerid
FROM #TableVariable
END
The above inserts one record into tbl_Responses for every row in #TableVariable.
The Problem
Instead of INSERT, I would like to perform an UPDATE, but I can't get the syntax right.
Thanks for any help...!
UPDATE
With some helpful hints, I was able to resolve this below...
You could try this (I haven't tested it) -
CREATE PROCEDURE sp_SaveResponses
(
#TableVariable SaveResponsesTableType READONLY
)
AS
BEGIN
UPDATE tbl_Responses set questionid = #TableVariable.questionid
FROM #TableVariable
WHERE #TableVariable.assessmentid = tbl_Response.assessmentid
END
Depending on what the join is between the table variable and the table that needs to be updated:
CREATE PROCEDURE sp_SaveResponses
(
#TableVariable SaveResponsesTableType READONLY
)
AS
BEGIN
UPDATE
tbl_Responses
SET
questionid = #TableVariable.questionid
FROM
#TableVariable T1
JOIN tbl_Responses T2 ON T1.assessmentid = T2.assessmentID
END
Thanks to #ipr1010 and #cob666 whose answers led me in the right direction... Here is the solution.
UPDATE tbl_Responses SET answerid = T1.answerid
FROM #TableVariable T1
WHERE tbl_Responses.assessmentid = T1.assessmentid AND tbl_Responses.questionid = T1.questionid
Naming #TableVariable T1 resolved the "must declare scalar variable..." issue.
I also needed to update my WHERE clause or all values were updated with the first value in #TableVariable.
I wish I could vote you guys up but apparently my street cred is too weak!