writing from a SQL view to a Table - sql

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.

Related

Call tabled function with parameters in 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

How to set a date variable with several days

I need to get a list of dates data. So far I'm only selecting one date at a time but I need it to be multiple days.
declare #evalDate1 as Date
declare #evalDate [date];
set #evalDate1 = '2020-10-20'
I tried this:
declare #evalDate1 as Date
declare #evalDate [date];
set #evalDate1 = ('2020-10-20' or '2020-10-21')
But this doesn't work. Can anyone help? Thank you!
you either need to make temp table
create table #evalDate ( value date)
insert into #evalDate values ('2020-10-20'), ('2020-10-21')
or a table variable
create #evalDate table ( value date)
insert into #evalDate values ('2020-10-20'), ('2020-10-21')

Query a table with json format

I would like to know how can I read with a sql query a table like that:
(this is just an example)
id,date,information
1,2018-26-02,{[{"iteration_number":0,"data":{"name":"Toto",values:{"PV":78,"SV":20,"TV":19},"state":"ok"},{"iteration_number":1,"data":{"name":"Baba",values:{"PV":68,"SV":10,"TV":11},"state":"ok"}}}]}
For example, to select the date of the first record, I will write: "SELECT date FROM table1 WHERE id=1;
But if I just would like the name of the iteration number 0 ? (Toto)
Say me if I'm not understandable.
Thanks for your response.
Simon
In MSSQL there is a JSON_VALUE function you can use for this:
More documentation can be found here.
DECLARE #temp_table TABLE
(
id INT NOT NULL IDENTITY(1, 1),
date DATETIME NOT NULL,
information VARCHAR(MAX) NOT NULL
);
INSERT INTO #temp_table
(date, information)
VALUES
(GETDATE(), '[{"iteration_number":1,"data":{"name":"Toto",values:{"PV":78,"SV":20,"TV":19},"state":"ok"},{"iteration_number":1,"data":{"name":"Baba",values:{"PV":68,"SV":10,"TV":11},"state":"ok"}}}]');
SELECT date, JSON_VALUE(information,'$[0].data.name') AS Name
FROM #temp_table

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 )

How to compare smalldatetime in stored procedure

I'm writing stored procedure to compare dates but it's not working properly. How can I make it so it compares only the dates but not the time? What I'm trying to do is compare the times and if the Id is null than insert a new entry with the same name but new time. I'm keeping multiple entries with same name but different test time.
ALTER PROCEDURE [dbo].[UL_TestData]
(
#Name varchar(30),
#Test_Time smalldatetime,
#ID INT output
)
AS
Declare #UpdateTime smalldatetime
SELECT #ID=ID FROM Info_User WHERE Name=#Name AND UpdateTime= #Test_Time
IF(#ID IS NULL)
BEGIN
INSERT INTO Info_User (Name, UpdateTime) VALUES (#Name, #UpdateTime)
END
there are a lot of solutions to this depending on what type of DBMS, however here is one:
SELECT #ID=ID FROM Info_User WHERE Name=#Name AND floor(cast(#UpdateTime as float))= floor(cast(#Test_Time as float))
this works because smalldatetime's date is stored a whole numbers, where the time is stored as decimals.
I would cast the dates to a plain date which makes this solution independent of implementation details
select #ID=ID
from info_user
where Name = #Name
and cast (UpdateTime as Date) = Cast(#TestTime as Date)
However, I would either add the date part of the UpdateTime as an additional (calculated) column or split the information into a date and a time part. This makes it much easier to query entries by the plain date.
As a rule of thumb: The type of columns (in general: the table layout) greatly depends on the type of query you usually run against your data.
Edit: As attila pointed out, the date datatype only exists in version 2008 and up