Call tabled function with parameters in sql - sql

I'm a newbie in SQL and with programming languages in general. I'm trying to make a tabled function in SQL (SQL Server):
CREATE FUNCTION dbo.fn_Get_List (
#PAR_user_code INT
, #PAR_id_session INT
, #PAR_id_profile INT
, #PAR_days_check_from DATETIME
, #PAR_days_check_to DATETIME
, #PAR_register BIT
)
RETURNS #tb_return table(
num_prat int,
num_ipotec int,
typeipotec tinyint,
fee money,
stipulated_date smalldatetime,
expire_date smalldatetime,
renew_date datetime,
delete_date date,
authentication_date date,
prime money)
AS
BEGIN
and then I have to call it in another sql page. I've tried to use this syntax:
DECLARE #PAR_user_code INT
DECLARE #PAR_id_session INT
DECLARE #PAR_id_profile INT
DECLARE #PAR_days_check_from DATETIME
DECLARE #PAR_days_check_to DATETIME
DECLARE #PAR_register BIT
SELECT *
FROM fn_IPO_Get_Elenco_Ipoteche(#PAR_user_code,#PAR_id_session,#PAR_id_profile,#PAR_days_check_from,#PAR_days_check_to,#PAR_register)
If I run my SELECT I don't have any result, because my parameters are not initialized.
How can I insert values into them? What I want to do is take values from a table that I've created and where I have these attributes and when I run my webpage I'll fill them.
For example, if I log with ID Session = 1, I'd like to see it into #PAR_id_session and then valorise the other parameters with the user's choices on the webpage (I have multiple choice for #PAR_days_check_from). How can I do it if I don't know the values?

Intialization of variable in T-SQL:
DECLARE #PAR_user_code INT = 1;
or by using SET:
SET #PAR_user_code = 1;
The function arguments can be populated from table using CROSS/OUTER APPLY:
SELECT *
FROM my_table t
CROSS APPLY fn_IPO_Get_Elenco_Ipoteche(t.user_code, ...) f
WHERE t.col = ? -- any condition

Related

Optimal way to SET/DECLARE a list in SQL query?

I am writing a SQL Query based of user input, as these inputs will change on a daily basis.
The goal of the query is to pull all data for only the ID's in the user-defined list. Example below-
However, I am getting the following error:
"Conversion failed when converting the varchar [...] to data type int"
Any idea on what the optimal way to specify a list and use that list at the "ID in (..)" clause?
I have tried converting the ID list into strings, but still receiving a similar error.
id_list = [12,16,22,42,1,24]
date = '2020-12-18'
query = (
"""
DECLARE #id varchar(1000), #date datetime
SET #id = '{}'
SET #date = '{}'
SELECT * from TABLE where ID in (#id) and Date = #Date
"""
.format(id_list,date))
The desired result is for a query to be able to take a list of IDs that could be utilized in the clause.
id in #id
SQL Server doesn't support lists or arrays. So the best method is a table:
declare #id_list table (id int);
insert into #idlist (id)
values (12), (16), (22), (42), (1), (24);
You can then use this wherever you would use a table variable. For instance:
where id in (select id from #id_list)

Compare datetime value in stored procedure

I am having trouble writing SQL Server queries/procedures with DateTime format in the tables.
My application runs on a standard ASP.NET MVC4 stack with SQL Server.
My table Bookings has this structure:
CREATE TABLE [dbo].[Bookings]
(
[BookingId] INT IDENTITY (1, 1) NOT NULL,
[ShowId] INT NOT NULL,
[RowId] INT NULL,
[Username] VARCHAR(100) NULL,
[PaymentId] INT NULL,
[ShowDate] DATETIME NULL,
.....
....
);
I have written two stored procedures where I am trying to compare table column ShowDate with different date parameters declared in stored procedure.
Procedure #1:
CREATE PROCEDURE [dbo].[GetBookingsByDate]
#venueid int,
#fromdate datetime,
#todate datetime
AS
BEGIN
SELECT
City, Title, ScreenTitle, ShowDate,
SUM([Qty]) AS Quantity,
SUM([Charges]) AS TotalAmount,
SUM([OtherCharges]) AS OtherCharges
FROM
ShowBookings
WHERE
Venueid = #venueid
AND ShowDate BETWEEN #fromdate AND #todate
GROUP BY
ScreenId, ShowDate, Venueid, Title, ScreenTitle, City
END
Procedure #2:
CREATE PROCEDURE [dbo].[GetAudienceReportsHistory]
#state varchar,
#city varchar,
#theaterName varchar,
#showdate datetime
AS
BEGIN
SELECT
b.BookingId, b.MobileNo, b.SeatNumbers, b.EmailId,
sc.ScreenTitle, sh.ShowTime, a.Title,
b.Username, b.SMSStatus
FROM
Bookings b
JOIN
Shows sh ON b.ShowId = sh.Id
JOIN
Venues AS v ON sh.Venue_Id = v.Id
JOIN
Artifacts a ON sh.Artifact_Id = a.Id
JOIN
Screens AS sc ON sh.Screen_ScreenId = sc.ScreenId
WHERE
b.ShowDate = #showdate
AND b.IsBooked = 'true'
AND b.TimeSolt = '0'
AND v.Title = #theaterName
AND v.City = #city
END
As you can see procedure #1 takes two datetime parameters, fromdate and todate. The second procedure takes only one datetime parameter showdate.
Procedure #1 returns the correct set of results, however procedure #2 returns no results at all. But I have crosschecked in the tables that I have proper data which should be returned for the Proc2 query. There seems to be some DateTime format mismatch.
I'm sending datetime parameters to the queries in "yyyy-mm-dd" format (eg: 2017-05-30). Inside the table the ShowDate column is stored in "dd-mm-yyyy" (eg: 30-05-2017) format.
I have tried sending the parameter in different date formats but I'm not getting any results for Proc2. Kindly help me in solving this. Thanks in advance. Let me know if you need more info.
you have to note that datetime includes time so when you equate that to a datetime field it will never be equal due to time difference... what you can do is cast both dates... meanwhile between captures time within the date
cast(showdate as date) = cast(#showdate as date)
or DateDIFF
datediff(day,#showdate,showdate) = 0
You Need to convert Date Proper Formate like this
CONVERT(date, b.ShowDate) = CONVERT(date,#showdate )

writing from a SQL view to a Table

Hello I've got this SQL View (Namely Login_Monitor) that I've created using a number of table joins
What I'm wanting to do now is to use a few columns in this View to write to a seperate table that I've created.
But Im gettiing Null values written to table instead of actual data.
This is how I created my destination table
create table MS_Login_Monitor
(date date,
time time,
USERID char(15),
COMPANY_NAME char(65),
LOGIN_DATE_TIME datetime,
TIME_SINCE_LAST_ACTION int,
)
This is the query I used to write view data to destination table
declare #date date
declare #time time
declare #USERID char(20)
declare #COMPANY_NAME char(65)
declare #LOGIN_DATE_TIME datetime
declare #TIME_SINCE_LAST_ACTION nchar(7)
set #date = CURRENT_TIMESTAMP
set #time = CURRENT_TIMESTAMP
select * from Login_Monitor
INSERT INTO DYNAMICS..MS_Login_Monitor (date, time,USERID, COMPANY_NAME, LOGIN_DATE_TIME, TIME_SINCE_LAST_ACTION)
VALUES (#date, #time,#USERID,#COMPANY_NAME, #LOGIN_DATE_TIME, #TIME_SINCE_LAST_ACTION)
could someone explain please why I get NULL values written to table please or if there are errors in my SQL query.
Thanks
You can try something like this;
INSERT INTO DYNAMICS..MS_Login_Monitor (date, time,USERID, COMPANY_NAME, LOGIN_DATE_TIME, TIME_SINCE_LAST_ACTION)
select #date, #time, X, Y.....(use actual column names of view) from Login_Monitor
You dont need other parameters.

inserting values from on table to another in sql server 2008 with one field should be incremented

declare #cid int
set #cid=(select ISNULL(MAX(cid),0)+1 from CustInfo)
insert into CustInfo(CID,CTypeId,CustNo,Regdate,
DOB,CCertID,CCertNo,CompId,PostedBy,PostedOn)
(select #cid,1,0,'2012-9-10',
dob,ccertid,ccertno,0,null,null
from updateCust3)
I have used above code to insert values from table updateCust3 to table UpdateCustInfo.
In this case the CID field should be incremented by one at each insert. I have used the above code but the cid doesn't seem to increase so the error is duplicate value for the primary key. So how can I increase the value of cid? Since the change in table property is not allowed I cannot use identity property.
try this:
declare #cid int
set #cid=(select ISNULL(MAX(cid),0)+1 from CustInfo)
insert into CustInfo(CID,CTypeId,CustNo,Regdate,
DOB,CCertID,CCertNo,CompId,PostedBy,PostedOn)
select #cid+row_number() over (order by (select 0)),1,0,'2012-9-10',
dob,ccertid,ccertno,0,null,null
from updateCust3)
Edit: As MikaelEriksson mentioned in the comment, this has the risk, if you users are simultaneously trying to update the table, it will error out..
have used a temp table to demonstrate. This is a better way to work to avoid errors when used by multiple users
DECLARE #Table TABLE
(
CTypeId INT identity (1,1)
,CustNo int
,DOB datetime
,Regdate datetime
,CCertID int
,CCertNo int
,CompId int
,PostedBy varchar(100)
,PostedOn datetime
)
INSERT #Table
select 1,0,'2012-9-10',
dob,ccertid,ccertno,0,null,null
from updateCust3

Must Declare Scalar

I have three separate table variables in my Function,
1 of them is not giving me any errors, the other two are,
I haven't found anything Different Syntax-wise between them, but maybe I need more caffeine.
the error I am receiving is
Must declare the scalar variable "#DispoTable".
DECLARE #CIDdisp INT
DECLARE #DispoTable TABLE
(
CaseID INT,
Code INT,
Description VARCHAR(150)
)
--Gather Data From filter
SELECT #CIDdisp = CaseID, #Code = Code, #Description = Description
FROM fnRecidFilter3(#CaseID,01,01)
-- Insert into Temp table
INSERT INTO #DispoTable (CaseID, Code, Description)
VALUES (#CIDdisp, #Code, #Description)
-- Merge the Temp Table with RecidReport Table
INSERT INTO RecidReport(Code, Description)
SELECT Code, Description
FROM #DispoTable
WHERE (#DispoTable.CaseID) = CaseID
is there something that I am missing?
You can't say:
WHERE (#DispoTable.CaseID) = CaseID
Instead you need to use an alias:
FROM #DispoTable AS d
WHERE d.CaseID = CaseID
But this clause makes no sense anyway. Did you mean to use a variable here? Perhaps:
FROM #DispoTable AS d
WHERE d.CaseID = #CIDdisp
?