Column Set to 0 Instead of Date Stored Procedure - sql

I am trying to set a column to the current date (in the form dd/mm/yyyy) in a stored procedure, however the column simply sets to 0. The code is as below:
USE [DBDataOne]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
declare #dateone varchar(max)
declare #dodate varchar(max)
select #dateone=convert(varchar,GETDATE(),103 )
select #dodate='Update [dbo].[tabfget] set DATEIN='+#dateone
exec (#dodate)

If datein is stored properly (as a date/time), then you don't need to worry about conversion.
Also, you don't need dynamic SQL for this. Just:
Update [dbo].[tabfget]
set DATEIN = cast(getdate() as date);
If -- horror of horrors -- you are storing dates as strings instead of the proper format, then you should fix the database. If that is not possible, you can do:
Update [dbo].[tabfget]
set DATEIN = convert(varchar(10), GETDATE(), 103);
However, if dates have to be stored as strings, then you should always use an ISO-standard format, such as YYYY-MM-DD.

Why can't you directly do like
Update [dbo].[tabfget] set DATEIN = #dateone
(OR)
Update [dbo].[tabfget] set DATEIN = convert(varchar,GETDATE(),103 )
Yes, the format/style 103 should get you / instead of - like
select GETDATE()
will result in 2015-05-29 20:43:38.547
select CONVERT(varchar(15), GETDATE(), 103)
Will result in 29/05/2015

Try this:
declare #dateone varchar(max)
declare #dodate varchar(max)
select #dateone=convert(varchar,GETDATE(),103 )
select #dodate='Update [dbo].[tabfget] set DATEIN='+quotename(#dateone,char(39));
Exec(#dodate);

You definitely should do the update without dynamic sql. But the reason for the zero is that you're not quoting the date as a literal and it gets evaluated as integer division. (Format 103 is mm/dd/yyyy.)

Related

How to pass GETDATE (Only date) as a parameter in sql server?

I want to pass the system date (GETDATE) only as a parameter in my SQL stored procedure. But I am getting an error while executing the procedure.
SQL query:
ALTER PROCEDURE ST_PRO_GETUSER
#D DATETIME = GETDATE --// passing GETDATE as a parameter.
AS BEGIN
select case when branch in ('A25','B10','C10')
then 'BR B1' Else 'BR B2'
end As [COLLECTION],FIXDATE
from MAIN_COUNTER where TDATE=#D --//Just want to pass date only
group by COLLECTION,FIXDATE
END
EXEC KK_SP_GETUSER_DIV
Error:
Conversion failed when converting date and/or time from character string.
What I have to do for it?
To pass as a parameter you just declare a variable and pass it in:
DECLARE #DATE DATETIME = GETDATE();
EXEC ST_PRO_GETUSER #DATE;
And if you want the date only, change the datatype of your parameter to a date and then do:
DECLARE #DATE DATE = GETDATE();
EXEC ST_PRO_GETUSER #DATE;
But part of your question seems to actually be asking how to specify a default parameter value. You can't use a function for the default value, so instead do:
CREATE PROCEDURE ST_PRO_GETUSER
(
#Date DATETIME = null
-- Change to DATE datatype if you don't want a time component.
-- #Date DATE = null
)
AS
BEGIN
SET NOCOUNT ON;
-- Default the #Date here is its null.
-- Note this doesn't handle the case when the caller wants to pass in null.
SET #Date = COALESCE(#Date,GETDATE());
-- SP Body
RETURN 0;
END
Solved My Self
ALTER PROCEDURE ST_PRO_GETUSER
#Date datetime = null
as
IF #Date is null
SET #Date = getdate() --// passing GETDATE as a parameter.
BEGIN
select case when branch in ('A25','B10','C10')
then 'BR B1' Else 'BR B2'
end As [COLLECTION],FIXDATE
from MAIN_COUNTER where TDATE=#D --//Just want to pass date only
group by COLLECTION,FIXDATE
END
EXEC ST_PRO_GETUSER
GETDATE() is the correct syntax, not GETDATE.

How to create/add columns using a variable in a loop

I am very new to SQL in that I just finished reading Sams Teach Yourself SQL in 10 Minutes and that is my only SQL knowledge. So now that I'm done with the book, I'm trying to create some tables so I can play around with them. I can easily create a table with a known amount of columns and specified header. Where I am having trouble is creating a table with an unknown amount of columns and a date as the header. What I have tried so far is this:
DECLARE #start_date AS DATE
DECLARE #end_date AS DATE
DECLARE #curr_date AS DATE
DECLARE #column_name AS CHAR(10)
SET #start_date = 2016-01-02
SET #end_date = 2016-12-31
SET #curr_date = #start_date
WHILE #curr_date < #end_date
SET #curr_date = DATEADD(DD, 7, #curr_date)
ALTER TABLE Project_1
ADD #curr_date DOUBLE
What I tried to do here is make a start and end point for the loop and use the loop condition which is stored in a local variable as my column header since that is what I need the column to be titled. I also tried using CAST to cast it as a char but the DBMS is delighted to let me know that there is Incorrect syntax near '#curr_date' on that last line (the ADD line) because it doesn't like that I'm trying to name a column with a local variable (I think). I don't have a sample output but the output should be a table with the first column defined as CHAR and titled emp_name because it will be holding names. All other columns defined as type DOUBLE and should be NULL because they will be holding a number of hours and must have the current date as the header #curr_date. I think all columns added to a table through the ALTER method are defaulted to NULL anyways. I've seen examples of dynamic SQL where you declare a variable to hold the select statement but I don't really understand how they add columns to a table. I'm not sure if this can be done in the CREATE statement but if it can that would be great to see. Also, this needs to be variable in the fact that I could change the #end_date to lets say... they year 2046.
Security is not an issue here
I agree with all of the comments about using ROWs not dynamically adding columns you can always dynamically pivot those latter and it will have more flexibily. So maybe some schema considerations but just to answer your specific question you where close.....
DECLARE #start_date AS DATE
DECLARE #end_date AS DATE
DECLARE #curr_date AS DATE
DECLARE #column_name AS CHAR(10)
SET #start_date = '2016-01-02'
SET #end_date = '2016-12-31'
SET #curr_date = #start_date
WHILE #curr_date < #end_date
BEGIN
DECLARE #SQL NVARCHAR(MAX)
SET #curr_date = DATEADD(DD, 7, #curr_date)
SET #SQL = 'ALTER TABLE TableB
ADD [' + CAST(#curr_date AS VARCHAR(10)) + '] FLOAT'
--PRINT #SQL
EXECUTE (#SQL)
END

use a variable in the table name when renaming a table in SQL

I am trying to rename a table in SQL Server 2008 R2 using the code below;
declare #date varchar(8)
set #date = convert( varchar(8), getdate(), 112)
exec sp_rename 'LM_SM_Billing_and_Send_Data', 'LM_SM_Billing_and_Send_Data_#date'
My intention is to rename the table with the current date appended.
select convert( varchar(8), getdate(), 112)
returns 20141219
but when I run the rename it names the table;
LM_SM_Billing_and_Send_Data_#date
instead of inserting the date
I'm wondering if it is possible to have it rename to;
LM_SM_Billing_and_Send_Data_20141219
by using the variable in the table name.
I've been googling quite a bit and things seem to point to using dynamic SQL, but I've never used it and not sure what the syntax would be to get the results I am looking for.
The issue you've ran into here, as John Saunders pointed out in his comment, SQL won't substitute the value of your variable into your parameter. (String interpolation)
Another issue you might run into, when trying to work around this problem, is concatenating in the procedure call. The following will also not work.
exec sp_rename 'LM_SM_Billing_and_Send_Data', 'LM_SM_Billing_and_Send_Data_' + #date
The reason the above will also error, is because a parameter can be either a variable, or a constant, not an expression as the above shows. If we declare #myNewName, and set the desired value into that variable, we can then pass that to the procedure.
Give this a try:
declare #date varchar(8)
set #date = convert( varchar(8), getdate(), 112)
declare #myNewName varchar(255) = 'LM_SM_Billing_and_Send_Data_' + #date
exec sp_rename 'LM_SM_Billing_and_Send_Data', #myNewName
This may be a good reference as one continues to work with SQL parameters: http://msdn.microsoft.com/en-us/library/ms189260(v=sql.105).aspx
Use Dynamic Sql to append the variable to the new table name.
Use select * into syntax to copy the data from new old table to new table this part has to be done dynamically.
Then finally drop the old table
declare #date varchar(8),
set #date = convert( varchar(8), getdate(), 112)
set #sql ='select * into LM_SM_Billing_and_Send_Data_'+#date+'
from LM_SM_Billing_and_Send_Data'
exec sp_executesql #sql
Drop table LM_SM_Billing_and_Send_Data

How to pass more than one values as parameter to sql statement?

I have one big SQL query and I want to pull out some data using that query
declare #Period VARCHAR(10) = 'MTD'
declare #Date DATETIME = '2011-08-31'
and I have a big select statement where I'm passing above parameters and it executes the output.
Now I have 10 different dates which I need to pass here each time to see the result.
How can I pass those date to above parameter declare #Date DATETIME how can I hard code it ?
So my desired output will be for those selected dates, give me hint for at least 3 dates ?
Use a table-valued parameter. First, create a type:
CREATE TYPE dbo.Dates AS TABLE(d DATE);
Now your stored procedure can take this type as a parameter:
CREATE PROCEDURE dbo.whatever
#d dbo.Dates READONLY
AS
BEGIN
SET NOCOUNT ON;
SELECT t.columns
FROM dbo.tableName AS t
INNER JOIN #d AS d
ON t.[date] = d.d;
END
GO
Then from your application you can pass this parameter in as a DataTable, for example.

HH:MM:SS:Msec to HH:MM:SS in stored procedure

I have a stored procedure which update a table based on such calculation and the calculation is done as column name (Calendatedate) - (Current System Date Time) and update this information to a column (TimeSpent) and display the value in Hh:Mm:SS:Msec format.
The query is working fine but I want to update it in such a way so that the time spent should be only HH:MM:SS format. Please help me that how I remove that Msec from the time spent.
CREATE procedure St_Proc_UpdateTimeSpent
#timeEntryID int,
#status int output
as begin
set nocount on;
declare #Date dateTime;
set #Date=GETDATE();
update Production set TimeSpent=(SELECT CONVERT(VARCHAR(20),DateAdd(SS,Datediff(ss,CalendarDate, #Date)%(60*60*24),0),114)),
IsTaskCompleted=1
where productionTimeEntryID=#timeEntryID
set #status=1;
return #status;
end
You can just use style 108 instead of 114 in the CONVERT function to get only the hh:mm:ss:
CREATE PROCEDURE dbo.St_Proc_UpdateTimeSpent
#timeEntryID int,
#status int output
AS BEGIN
SET NOCOUNT ON;
DECLARE #Date DATETIME;
SET #Date = GETDATE();
UPDATE dbo.Production
SET TimeSpent = CONVERT(VARCHAR(20), DATEADD(SS, DATEDIFF(ss, CalendarDate, #Date)%(60*60*24),0), 108),
IsTaskCompleted = 1
WHERE
productionTimeEntryID = #timeEntryID
SET #status = 1;
RETURN #status;
END
See the excellent MSDN documentation on CAST and CONVERT for a comprehensive list of all supported styles when converting DATETIME to VARCHAR (and back)
BTW: SQL Server 2008 also introduced a TIME datatype which would probably be a better fit than a VARCHAR to store your TimeSpent values ... check it out!