empty string changing to 0 for int - sql

Very unique..... and not authorized to change collation
i have created a table
CREATE TABLE BT_INPUT_CHK
(
[ID] [int] NOT NULL,
[RELID] [int] NULL,
[OPNO] [varchar](35) NULL
)
and when i am inserting data
INSERT ZBT_INPUT_CHK ([ID],[RELID],[OPNO])
VALUES('1000002','','')
the problem starts here.
for varchar empty string inserted as same, but for int empty string is changing to 0.
collation: Latin1_General_CI_AS
can anyone please help me on this.
Thanks

When empty sting is implicitly converted to INT it converts to ZERO. if you need to set it to NULL then use NULLIF function.
DECLARE #RELID VARCHAR(10) = ''
INSERT ZBT_INPUT_CHK ([ID],[RELID],[OPNO])
VALUES('1000002',NULLIF(#RELID,''),'')

Check This..You will get clear idea on Inserting Empty String to Numeric Column
INSERT into BT_INPUT_CHK ([ID],[RELID],[OPNO]) VALUES('1000007',NULL,'');

try this,
CREATE TABLE #BT_INPUT_CHK
(
[ID] [int] NOT NULL,
[RELID] [int] NULL,
[OPNO] [varchar](35) NULL
)
INSERT #BT_INPUT_CHK ([ID],[RELID],[OPNO])
VALUES('1000002',(case when cast('' as varchar(10))='' then 'Error' else '' end),'')

Related

Add range values to include exiting table partition in Azure synapse Analytics

I need to add a new boundary value to the existing table .
CREATE TABLE [STG].[IHS_POLK]
(
[CCYYQ_NBR] [decimal](5, 0) NOT NULL,
[COUNTRY] [varchar](2) NOT NULL,
[STATE] [varchar](35) NOT NULL,
[COUNTY] [varchar](35) NOT NULL,
[ZIP] [varchar](6) NOT NULL,
[TOTAL] [varchar](10) NULL
)
WITH
(
DISTRIBUTION = ROUND_ROBIN,
CLUSTERED COLUMNSTORE INDEX,
PARTITION
([CCYYQ_NBR] RANGE LEFT FOR VALUES (20191, 20192, 20193, 20194, 20201, 20202, 20203, 20204, 20211, 20212, 20213, 20214, 20221, 20222, 20223, 20224, 20231, 20232, 20233, 20234, 20241, 20242, 20243, 20244, 20251, 20252, 20253, 20254))
)
GO
Now I need to add a value "20261" in the range . Please let me know the query to add.
You can use alter statement as below, if data exists in table, disable column store index before and rebuild it after running this. Refer this document for more details.
ALTER TABLE [STG].[IHS_POLK] SPLIT RANGE (20261);

Need to have a Trigger on Table with Encrypted Column in SQL Server that inserts a new record for each update into Archive Table

I have a table similar to following schema in SQL Server 2017:
Table Sample in the main database where TaxID column is encrypted using SQL Server "Always Encrypted" feature:
CREATE TABLE [dbo].[Sample]
(
[CreatedDt] [smalldatetime] NOT NULL,
[LastModDt] [smalldatetime] NOT NULL,
[CompanyID] [int] IDENTITY(1,1) NOT NULL,
[CompanyName] [varchar](250) NOT NULL,
[CompanyTaxName] [varchar](250) NULL,
[TaxID] [varchar](15) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY =
[CEK_Auto1], ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL,
[Active] [bit] NOT NULL
)
Then we have another table with same schema in archive database for history purposes with TaxID encrypted.
This is the table Sample in the Main_Archive database:
CREATE TABLE [dbo].[Sample]
(
[CreatedDt] [smalldatetime] NOT NULL,
[LastModDt] [smalldatetime] NOT NULL,
[CompanyArchiveID] [int] IDENTITY(1,1) NOT NULL,
[CompanyID] [int] IDENTITY(1,1) NOT NULL,
[CompanyName] [varchar](250) NOT NULL,
[CompanyTaxName] [varchar](250) NULL,
[TaxID] [varchar](15) COLLATE Latin1_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY =
[CEK_Auto1], ENCRYPTION_TYPE = Deterministic, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NOT NULL,
[Active] [bit] NOT NULL
)
Now, we want to have a trigger on the main Sample table that inserts a new record into the archive Sample table for every update.
The trigger for the Sample table in the main database is as follows:
CREATE TRIGGER [dbo].[tr_iud_Sample]
ON [dbo].[Sample]
FOR INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON
DECLARE #CurrDt AS SMALLDATETIME
SELECT #CurrDt = GETDATE()
DECLARE #CurrYear AS INT
SELECT #CurrYear = YEAR(#CurrDt)
UPDATE Sample
SET LastModDt = #CurrDt,
CreatedDt = CASE WHEN d.CompanyID IS NULL THEN #CurrDt ELSE Sample.CreatedDt END
FROM inserted i WITH (NOLOCK)
LEFT JOIN deleted d WITH (NOLOCK) ON d.CompanyID= i.CompanyID
WHERE Sample.CompanyID = i.CompanyID
INSERT INTO [Main_Archive].[dbo].Sample
SELECT CreatedDt, LastModDt, CompanyID, CompanyName, CompanyTaxName, TaxID, Active
FROM deleted
END
ALTER TABLE [dbo].[Sample] ENABLE TRIGGER [tr_iud_Sample]
GO
ALTER TABLE [dbo].[Vendor] DISABLE TRIGGER [tr_iud_Sample]
GO
But this fails and I get this error:
Msg 4920, Level 16, State 0, Line 50
Operand type clash: varchar(15) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto1', column_encryption_key_database_name = 'NCI_COMMON') collation_name = 'Latin1_General_BIN2' is incompatible with varchar
Is there a way to have a trigger on encrypted table and if so, how to achieve the
desired functionality?
Also, if SQL Server currently does not support that, is there any work around to achieve that?
Thank you in advance
As you are using Always Encrypted your SQL Server version System-Versioned Temporal Tables.
You can make your table system-versioned and leave the work of maintaining the history to the SQL Server Engine (also, when you are changing your table design, the engine will mitigate the changes to the history table).
Temporal tables can be queried using special clauses and bring to you new ways for analyzing historical data.
One disadvantage I have faced is that the history table columns must match the target table ones - so, if you need to have a ModifiedBy column in the history, you must change your application to populate such value in the original table.

SQL Insert - String or binary data would be truncated for INT values

I'm getting the "String or binary data would be truncated" error when trying to insert integers to one of my tables.
I've read several post about the length of the column vs the length of the value one is inserting, but it doesn't seem to be my case once the columns are all int or smallint type and the values are all maximum two digits.
The table structure is the following:
CREATE TABLE [tblvUserLocation] (
[User_Location_ID] [int] IDENTITY (1, 1) NOT NULL ,
[Location_ID] [int] NULL ,
[Line_Type_ID] [int] NULL ,
[User_ID] [int] NULL ,
[Active] [smallint] NULL CONSTRAINT [DF_tblvUserLocation_Active] DEFAULT (1),
[Last_Updated] [smalldatetime] NULL CONSTRAINT [DF_tblvUserLocation_Last_Updated] DEFAULT (getdate()),
[Last_Updated_By] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_tblvUserLocation_Last_Updated_By] DEFAULT (suser_sname())
) ON [PRIMARY]
GO
The insert I'm trying to run is the following:
insert into tblvUserLocation (Location_ID, Line_Type_ID, [User_ID], Active)
values (20, 2, 41, 1)
And the error I'm getting is the following:
Server: Msg 8152, Level 16, State 2, Line 1 String or binary data
would be truncated. The statement has been terminated.
If that makes any difference, I'm using SQL Server 2000.
Please let me know what your thoughts are.
Thanks!
Looks like the problem comes from your [DF_tblvUserLocation_Last_Updated_By] constraint.
It's pulling the current username which is more than likely longer than the length of your [Last_Updated_By] column VARCHAR(10).
Update your DDL to:
[Last_Updated_By] [varchar] (128)

how to set default value for a column using a scalar function

I have table like this:
CREATE TABLE [dbo].[tbl](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Year] [int] NOT NULL,
[Month] [int] NOT NULL,
[Fields] [xml] NOT NULL,
[NameFromXML] [nvarchar](1000) NULL
) ON [PRIMARY]
in Fields column I stor XML like this:
<Employees>
<Person>
<ID>0</ID>
<Name>Ligha</Name>
<LName>Agha</LName>
</Person>
</Employees>
Ok.I want persist value of Name element to NameFromXML.I write this function :
CREATE FUNCTION dbo.GetName
(
#xml XML
)
RETURNS NVARCHAR(100)
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN
RETURN #xml.value('/Employees[1]/Person[1]/Name[1]', 'nvarchar(100)')
END
GO
but when I write this code to add default:
ALTER TABLE tbl_Test_XML_Index_View ADD CONSTRAINT df_f DEFAULT(dbo.GetName(Fields))
FOR namefromXML
I got this error:
The name "Fields" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
How I can solve this problem?
Why not have it as a computed column, which will always be correct, and won't require any more maintenance effort:
CREATE FUNCTION dbo.GetName
(
#xml XML
)
RETURNS NVARCHAR(100)
WITH RETURNS NULL ON NULL INPUT
, SCHEMABINDING
AS
BEGIN
RETURN #xml.value('/Employees[1]/Person[1]/Name[1]', 'nvarchar(100)')
END
GO
CREATE TABLE [dbo].[tbl](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Year] [int] NOT NULL,
[Month] [int] NOT NULL,
[Fields] [xml] NOT NULL,
[NameFromXML] AS dbo.GetName(Fields) persisted
) ON [PRIMARY]
insert into dbo.tbl (Year,Month,Fields)
select 1,1,'<Employees>
<Person>
<ID>0</ID>
<Name>Ligha</Name>
<LName>Agha</LName>
</Person>
</Employees>'
select * from dbo.tbl
I had to add SCHEMABINDING to the function, in order for it to be treated as deterministic. That, in turn, allowed me to mark the computed column as persisted, which means it can, in turn, be indexed if needed.
It seems that you are trying to store redundant data for each row. What happens if somehow that name in the XML is changed? How do you take care to update the NameFromXML column? By using triggers? I can give you the advise, to just store data you need by using regular columns. Write insert/update stored procedures with will take the XML as a parameter, and insert data from it into the appropriate columns.

Sql Server - Insufficient result space to convert uniqueidentifier value to char

I am getting below error when I run sql query while copying data from one table to another,
Msg 8170, Level 16, State 2, Line 2
Insufficient result space to convert
uniqueidentifier value to char.
My sql query is,
INSERT INTO dbo.cust_info (
uid,
first_name,
last_name
)
SELECT
NEWID(),
first_name,
last_name
FROM dbo.tmp_cust_info
My create table scripts are,
CREATE TABLE [dbo].[cust_info](
[uid] [varchar](32) NOT NULL,
[first_name] [varchar](100) NULL,
[last_name] [varchar](100) NULL)
CREATE TABLE [dbo].[tmp_cust_info](
[first_name] [varchar](100) NULL,
[last_name] [varchar](100) NULL)
I am sure there is some problem with NEWID(), if i take out and replace it with some string it is working.
I appreciate any help. Thanks in advance.
A guid needs 36 characters (because of the dashes). You only provide a 32 character column. Not enough, hence the error.
You need to use one of 3 alternatives
1, A uniqueidentifier column, which stores it internally as 16 bytes. When you select from this column, it automatically renders it for display using the 8-4-4-4-12 format.
CREATE TABLE [dbo].[cust_info](
[uid] uniqueidentifier NOT NULL,
[first_name] [varchar](100) NULL,
[last_name] [varchar](100) NULL)
2, not recommended Change the field to char(36) so that it fits the format, including dashes.
CREATE TABLE [dbo].[cust_info](
[uid] char(36) NOT NULL,
[first_name] [varchar](100) NULL,
[last_name] [varchar](100) NULL)
3, not recommended Store it without the dashes, as just the 32-character components
INSERT INTO dbo.cust_info (
uid,
first_name,
last_name
)
SELECT
replace(NEWID(),'-',''),
first_name,
last_name
FROM dbo.tmp_cust_info
I received this error when I was trying to perform simple string concatenation on the GUID. Apparently a VARCHAR is not big enough.
I had to change:
SET #foo = 'Old GUID: {' + CONVERT(VARCHAR, #guid) + '}';
to:
SET #foo = 'Old GUID: {' + CONVERT(NVARCHAR(36), #guid) + '}';
...and all was good. Huge thanks to the prior answers on this one!
Increase length of your uid column from varchar(32) ->varchar(36)
because guid take 36 characters
Guid.NewGuid().ToString() -> 36 characters
outputs: 12345678-1234-1234-1234-123456789abc
You can try this. This worked for me.
Specify a length for VARCHAR when you cast/convert a value..for uniqueidentifier use VARCHAR(36) as below:
SELECT Convert (varchar(36),NEWID()) AS NEWID
The default length for VARCHAR datatype if we don't specify a length during CAST/CONVERT is 30..
Credit : Krishnakumar S
Reference : https://social.msdn.microsoft.com/Forums/en-US/fb24a153-f468-4e18-afb8-60ce90b55234/insufficient-result-space-to-convert-uniqueidentifier-value-to-char?forum=transactsql