Convert text to datetime, and select between two dates - sql-server

I'm trying to get some values between two dates (the 100 last days). However my column is a text-field, formatted: 17.06.2013
SELECT
.....
WHERE Organizations.OrganizationID = '4360'
AND convert(datetime,convert(varchar(10),StatisticsDate),104) BETWEEN
convert(datetime,GETDATE()-100,104) AND convert(datetime,GETDATE(),104)
GROUP BY Groups.Name, GroupStatistics.StatisticsDate
Mssql error:
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.
Can someone please tell me what I'm doing wrong?
Thank you! :-)
UPDATE:
[GroupStatisticsID] [int] IDENTITY(1,1) NOT NULL,
[GroupID] [int] NOT NULL,
[CreateUser] [nvarchar](max) NULL,
[StatisticsDate] [text] NULL,
[memberAttendants] [int] NOT NULL,
[Free] [int] NULL,
[FreeHours] [int] NULL,
[GroupName] [text] NULL,
[GroupNumber] [int] NULL,
[Ser] [text] NULL,
[SerNmbr] [int] NULL,
[SerName] [text] NULL
UPDATE2:
I tried SELECT GETDATE() which gave me: 2013-06-18 22:38:25:270
Does that mean I need to convert to this formatting to use BETWEEN?

The date comparision with between is not the problem in your case, since you casted already.
You will have to Group with Not text values:
GROUP BY Name, convert(datetime,convert(varchar(10),StatisticsDate),104)

Related

Error while querying the partitioned table in SQL Server

I have created a partition table and trying to query the partition but not able to do so in sql server 2016. Could somebody tell me where I am going wrong
CREATE PARTITION FUNCTION [financialStatementPartition](datetime)
AS RANGE RIGHT FOR VALUES (N'2013-01-01T00:00:00.000', N'2014-01-01T00:00:00.000',
N'2015-01-01T00:00:00.000', N'2016-01-01T00:00:00.000',
N'2017-01-01T00:00:00.000')
GO
Table schema
CREATE TABLE [dbo].[FinancialStatementIds]
(
[financialCollectionId] [int] NOT NULL,
[companyId] [int] NOT NULL,
[dataItemId] [int] NOT NULL,
[dataItemName] [varchar](200) NULL,
[dataItemvalue] [decimal](18, 0) NULL,
[unittypevalue] [int] NULL,
[fiscalyear] [int] NULL,
[fiscalquarter] [int] NULL,
[periodenddate] [datetime] NULL,
[filingdate] [datetime] NULL,
[restatementtypename] [varchar](200) NULL,
[latestforfinancialperiodflag] [bit] NULL,
[latestfilingforinstanceflag] [bit] NULL,
[currencyconversionflag] [int] NULL,
[currencyname] [varchar](200) NULL,
[periodtypename] [varchar](200) NULL
)
Query
SELECT *
FROM dbo.FinancialStatementIds
WHERE $PARTITION.financialStatementPartition(periodenddate) = '2013-01-01T00:00:00.000'
Error
Conversion failed when converting the varchar value '2013-01-01T00:00:00.000' to data type int.
Use following query instead:
SELECT *
FROM dbo.FinancialStatementIds
WHERE periodenddate = '20130101'
Anyway, the table is still not partitioned properly. You need to apply Partition Scheme to connect the table and Partition function.

Unable to figure out SQL query for a task

I have database with following tables
Login table:
CREATE TABLE [dbo].[Login]
(
[username] [nvarchar](100) NOT NULL,
[password] [nvarchar](50) NOT NULL,
[user_type] [nchar](10) NOT NULL,
[id] [int] IDENTITY(1,1) NOT NULL,
[isDelete] [bit] NOT NULL,
)
Test table:
CREATE TABLE [dbo].[Test]
(
[TestId] [int] IDENTITY(1,1) NOT NULL,
[TestName] [nvarchar](100) NOT NULL,
[UserId] [int] NOT NULL,
[isDelete] [bit] NOT NULL,
)
Questions table:
CREATE TABLE [dbo].[Questions]
(
[Qid] [int] IDENTITY(1,1) NOT NULL,
[Tid] [int] NOT NULL,
[Qtype] [int] NOT NULL,
[Question] [nvarchar](max) NOT NULL,
[isDelete] [bit] NULL,
)
Login.id is a foreign key and references Test.UserId
Test.TestId is foreign key and references Questions.Tid
My question is: I want to fetch Login.username, Test.TestName and the number of questions per test, e.g. I want all tests present and number of questions per test (even if 0).
I tried the following query
select
Test.TestId, Test.TestName, COUNT(Questions.Tid) as 'No.Of Questions'
from
Test, Questions
where
Test.TestId = Questions.Tid and
Questions.isDelete <> 'true'
group by
TestId, TestName
but this query only returns the tests for which at least single question is present in questions table.
I want all tests compulsory and then questions per test.
you need to use Left outer join
select T.TestId,T.TestName,COUNT(Q.Tid) as [No.Of Questions]
from Test t
Left Join Questions q
On Q.isDelete<>'true'
and T.TestId=Q.Tid
group by TestId,TestName
your current syntax works like Inner Join. Thats the reason you are getting tests which is not having any questions

show records after current time

Actually I want some records from my database. There is a field Time_From. I just want to show only those records which are after DateTime.Now().
But it is not showing, it shows records before and after DateTime.Now()
Select *
from mytable
where Vehicle_Booking_Date= #Vehicle_Booking_Date
AND Time_From > #Time_From order by Time_From"
The table definition (from the comment)
CREATE TABLE [dbo].[mtblVehicle_Booking]
(
[Sno] [int] IDENTITY(1,1) NOT NULL,
[Vehicle_Number] [nvarchar](100) NULL,
[Vehicle_Booking_Date] [datetime] NULL,
[Time_From] [datetime] NULL,
[Time_To] [datetime] NULL,
[Vehicle_Used_By] [varchar](100) NULL,
[Vehicle_Booked_By] [varchar](100) NULL,
[Cost_Code] [nvarchar](50) NULL,
[Budget_Line] [nvarchar](50) NULL,
[Purpose] [varchar](20) NULL,
[Destination] [nvarchar](500) NULL,
[Trip_Details] [nvarchar](500) NULL
)
ON [PRIMARY]
If you want to select all records whose Time_From is greater than current time and date is equal to specified date,
Select *
from mytable
where Vehicle_Booking_Date= #Vehicle_Booking_Date
AND Time_From > now() order by Time_From'
You have not mentioned what database you are using. But concept remains same. Just substract the other date time from current time. If it is greater than 0 it means that the given date time is greater than the current date time.
Sample SQL
Select *
from mytable
where Vehicle_Booking_Date= #Vehicle_Booking_Date
AND DATEDIFF(Time_From,SYSDATETIME()) > 0
Hope this helps.

SQL Server BULK INSERT FROM different schemas

I have a database that can have data updated from two external parties.
Each of those parties sends a pipe delimited text file that is BULK INSERTED into the staging table.
I now want to change the scheme for one of the parties by adding a few columns, but this is unfortunately breaking the BULK INSERT for the other party even though the new columns are all added as NULLABLE.
Is there any obvious solution to this?
TABLE SCHEMA:
CREATE TABLE [dbo].[CUSTOMER_ENTRY_LOAD](
[CARD_NUMBER] [varchar](12) NULL,
[TITLE] [varchar](6) NULL,
[LAST_NAME] [varchar](34) NULL,
[FIRST_NAME] [varchar](40) NULL,
[MIDDLE_NAME] [varchar](40) NULL,
[NAME_ON_CARD] [varchar](26) NULL,
[H_ADDRESS_PREFIX] [varchar](50) NULL,
[H_FLAT_NUMBER] [varchar](5) NULL,
[H_STREET_NUMBER] [varchar](10) NULL,
[H_STREET_NUMBER_SUFFIX] [varchar](5) NULL,
[H_STREET] [varchar](50) NULL,
[H_SUBURB] [varchar](50) NULL,
[H_CITY] [varchar](50) NULL,
[H_POSTCODE] [varchar](4) NULL,
[P_ADDRESS_PREFIX] [varchar](50) NULL,
[P_FLAT_NUMBER] [varchar](5) NULL,
[P_STREET_NUMBER] [varchar](10) NULL,
[P_STREET_NUMBER_SUFFIX] [varchar](5) NULL,
[P_STREET] [varchar](50) NULL,
[P_SUBURB] [varchar](50) NULL,
[P_CITY] [varchar](50) NULL,
[P_POSTCODE] [varchar](4) NULL,
[H_STD] [varchar](3) NULL,
[H_PHONE] [varchar](7) NULL,
[C_STD] [varchar](3) NULL,
[C_PHONE] [varchar](10) NULL,
[W_STD] [varchar](3) NULL,
[W_PHONE] [varchar](7) NULL,
[W_EXTN] [varchar](5) NULL,
[DOB] [smalldatetime] NULL,
[EMAIL] [varchar](50) NULL,
[DNS_STATUS] [bit] NULL,
[DNS_EMAIL] [bit] NULL,
[CREDITCARD] [char](1) NULL,
[PRIMVISACUSTID] [int] NULL,
[PREFERREDNAME] [varchar](100) NULL,
[STAFF_NUMBER] [varchar](50) NULL,
[CUSTOMER_ID] [int] NULL,
[IS_ADDRESS_VALIDATED] [varchar](50) NULL
) ON [PRIMARY]
BULK INSERT STATEMENT:
SET #string_temp = 'BULK INSERT customer_entry_load FROM '+char(39)+#inpath
+#current_file+'.txt'+char(39)+' WITH (FIELDTERMINATOR = '+char(39)+'|'+char(39)
+', MAXERRORS=1000, ROWTERMINATOR = '+char(39)+'\n'+char(39)+')'
SET DATEFORMAT dmy
EXEC(#string_temp)
The documentation describes how to use a format file to handle the scenario where the target table has more columns than the source file. An alternative that can sometimes be easier is to create a view on the table and BULK INSERT into the view instead of the table; this possibility is described in the same documentation.
And please always mention your SQL Server version.
Using OPENROWSET with BULK allows you to use your file in a query. You can use that to format the data and select only the columns you need.
In the end I have handled the two different cases with two different BULK INSERT statements (depending on which file is being processed). It seems like there isn't a way to do what I was trying to do with one statement.
You could use the format file idea supplied by #Pondlife.
Adapt your insert dynamically based on the input file name (provided there are unique differneces between the external parties). Using a CASE statement, simply select the correct format file based on the unique identifier in the file name.
DECLARE #formatFile varchar (max);
Set #formatFile =
CASE
WHEN #current_file LIKE '%uniqueIdentifier%'
THEN 'file1'
ELSE 'file2'
END
SET #string_temp = 'BULK INSERT customer_entry_load FROM '+char(39)+#inpath
+#current_file+'.txt'+char(39)+' WITH (FORMATFILE = '+char(39)+#formatFile+char(39)
')'
SET DATEFORMAT dmy
EXEC(#string_temp)
Hope that helps!

TSQL Help (SQL Server 2005)

I have been playing around with a quite complex SQL Statement for a few days, and have gotten most of it working correctly.
I am having trouble with one last part, and was wondering if anyone could shed some light on the issue, as I have no idea why it isnt working:
INSERT INTO ExistingClientsAccounts_IMPORT
SELECT DISTINCT
cca.AccountID, cca.SKBranch, cca.SKAccount, cca.SKName, cca.SKBase,
cca.SyncStatus, cca.SKCCY, cca.ClientType, cca.GFCID, cca.GFPID, cca.SyncInput,
cca.SyncUpdate, cca.LastUpdatedBy, cca.Deleted, cca.Branch_Account, cca.AccountTypeID
FROM ClientsAccounts AS cca
INNER JOIN
(SELECT DISTINCT ClientAccount, SKAccount, SKDesc,
SKBase, SKBranch, ClientType, SKStatus, GFCID,
GFPID, Account_Open_Date, Account_Update
FROM ClientsAccounts_IMPORT) AS ccai
ON cca.Branch_Account = ccai.ClientAccount
Table definitions follow:
CREATE TABLE [dbo].[ExistingClientsAccounts_IMPORT](
[AccountID] [int] NOT NULL,
[SKBranch] [varchar](2) NOT NULL,
[SKAccount] [varchar](12) NOT NULL,
[SKName] [varchar](255) NULL,
[SKBase] [varchar](16) NULL,
[SyncStatus] [varchar](50) NULL,
[SKCCY] [varchar](5) NULL,
[ClientType] [varchar](50) NULL,
[GFCID] [varchar](10) NULL,
[GFPID] [varchar](10) NULL,
[SyncInput] [smalldatetime] NULL,
[SyncUpdate] [smalldatetime] NULL,
[LastUpdatedBy] [varchar](50) NOT NULL,
[Deleted] [tinyint] NOT NULL,
[Branch_Account] [varchar](16) NOT NULL,
[AccountTypeID] [int] NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[ClientsAccounts_IMPORT](
[NEWClientIndex] [bigint] NOT NULL,
[ClientGroup] [varchar](255) NOT NULL,
[ClientAccount] [varchar](255) NOT NULL,
[SKAccount] [varchar](255) NOT NULL,
[SKDesc] [varchar](255) NOT NULL,
[SKBase] [varchar](10) NULL,
[SKBranch] [varchar](2) NOT NULL,
[ClientType] [varchar](255) NOT NULL,
[SKStatus] [varchar](255) NOT NULL,
[GFCID] [varchar](255) NULL,
[GFPID] [varchar](255) NULL,
[Account_Open_Date] [smalldatetime] NULL,
[Account_Update] [smalldatetime] NULL,
[SKType] [varchar](255) NOT NULL
) ON [PRIMARY]
The error message I get is:
Msg 8152, Level 16, State 14, Line 1
String or binary data would be truncated.
The statement has been terminated.
The error is because you are trying to insert data into a column in ExistingClientsAccounts_IMPORT where the column size is smaller than the length of data attempting to be inserted into it.
e.g.
SKAccount column is VARCHAR(12) in the ExistingClientsAccounts_IMPORT table but is VARCHAR(255) in ClientsAccounts_IMPORT.
So if ClientsAccounts_IMPORT contains any rows where that field is longer than 12 characters, you will get that error as obv. e.g. 100 characters will not fit into a 12 character field.
You need to make sure all the columns in the table you are inserting into, are big enough - make sure each column definition matches the source table.
The third column of your SELECT column list means that ExistingClientsAccounts_IMPORT.SKAccount is populated from ClientsAccounts.SKAccount - however, the source is up to 255 characters, while the destination has a capacity of 12. If there's any data that wouldn't fit, you'll get this message.
I haven't gone through all the other columns.
You are trying to insert values which are greater than tha max length specified for a column. Use a profiler to check the data being passed to this query and verify the length of data against the permissible length for all columns.
There is a clear mismatch in the column lenghts of common columns of these two tables.
ClientsAccounts_IMPORT.SKBase is 10 whereas it is 16 in the other table.
Check the field definitions. You can see some are smaller than the original ones. Now run a query on the old data - you will find some of the larger fields were used, so the insert is not possible without losing data.
Example: SKAccount - from 255 length to 12.

Resources