Merge stored procedure - sql

CREATE TABLE [dbo].[SupplierTableType](
[Supplier_ID] [nvarchar](10) NULL,
[Supplier_Name] [nvarchar](50) NULL,
[Address1] [nvarchar](30) NULL,
[Address2] [nvarchar](30) NULL,
[Address3] [nvarchar](30) NULL,
)
GO
--------------------Procedure----------------------
CREATE PROCEDURE [dbo].[Update_SupplierTable]
#TblSupplierTable SupplierTableType READONLY
AS
BEGIN
SET NOCOUNT ON;
MERGE INTO SupplierTable c1
USING #TblSupplierTable c2
ON c1.Supplier_ID=#TblSupplierTable.Supplier_ID
WHEN MATCHED THEN
UPDATE SET
c1.[Supplier_Name]= c2.[Supplier_Name]
, c1.[Address1]=c2.[Address1]
, c1.[Address2]=c2.[Address2]
, c1.[Address3]=c2.[Address3]
WHEN NOT MATCHED THEN
INSERT VALUES( #TblSupplierTable.[Supplier_Name],
c2.[Address1],
c2.[Address2],
c2.[Address3]
);
END
Msg 2715, Level 16, State 3, Procedure Update_SupplierTable, Line 3 [Batch Start Line 56]
Column, parameter, or variable #1: Cannot find data type SupplierTableType.
Parameter or variable '#TblSupplierTable' has an invalid data type.
Msg 1087, Level 16, State 1, Procedure Update_SupplierTable, Line 8 [Batch Start Line 56]
Must declare the table variable "#TblSupplierTable".

Instead of creating a table, you have to create a data type for SupplierTableType.
I.e. instead of
CREATE TABLE SupplierTableType...
you have to use
CREATE TYPE SupplierTableType AS TABLE ...
See the docs for further info.

Related

Unclosed quotation mark after the character

I try to update my table by creating a temporary table, when I run the query in my local DB i get no issue, but when I run it in production DB I get this issue:
Msg 105, Level 15, State 1, Line 1012
Unclosed quotation mark after the character string 'PostCode
'.
Msg 102, Level 15, State 1, Line 1012
Incorrect syntax near 'PostCode
'.
Here is the line of code that throws the error:
INSERT [dbo].[#TempPostalCode] ([PostCode], [PostIn], [Bus], [CustomerPLId], [Box-In_Service])
VALUES (13189, 1, 1, 0, 0)
Update:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[#TempPostalCode](
[PostCode] [float] NULL,
[PostIn] [float] NULL,
[Bus] [float] NULL,
[CustomerPLId] [float] NULL,
[Box-In_Service] [float] NULL
) ON [PRIMARY]
GO

Msg 207, Level 16, State 1 "Invalid column name 'Name'"

I'm trying to drop and recreate a table with a new schema in SQL Server, and then insert some test data into it to validate that it's working correctly. I have the following DDL:
CREATE TABLE [dbo].[Product](
[ID] int IDENTITY(1,1) PRIMARY KEY,
[Name] VARCHAR(100) NOT NULL,
[Description] VARCHAR(200) NULL,
[Modified] DATETIME NOT NULL DEFAULT(GETUTCDATE()),
[ModifiedBy] VARCHAR(32) NOT NULL
);
and the following insert statement:
INSERT INTO [dbo].[Product]([Name], [Description], [Modified], [ModifiedBy])
VALUES('Test', 'Description', GETUTCDATE(), 'Me');
Whenever I attempt to insert the aforementioned row, I get an error:
Msg 207, Level 16, State 1, Line 38
Invalid column name 'Name'.
Msg 207, Level 16, State 1, Line 38
Invalid column name 'Description'.
I know the table is there since I can SELECT * FROM Product and get an empty result set with the correct columns and no errors... I just can't insert into it for some reason. Any help would be greatly appreciated!
As per Martin's answer, I did some more research and he is correct. The schema manipulation needs to be done in separate batches (I simply added a GO after dropping my old table and after creating my new one with a different schema). A more detailed answer can be found here: "Invalid column name" error when calling insert after table created
Maybe try refreshing the cache. Easy way is to press Ctrl + shift + R
Or
Edit > IntelliSense > Refresh Local Cache
If doesnt work, then use qualified names [dbo].table or username.tablename etc
More here: http://msdn.microsoft.com/en-us/library/ms174205.aspx
For me, your query looks good, and i test it successfully.
Try adding schema name and put all column name inside brackets:
CREATE TABLE [dbo].[Product](
[ID] int IDENTITY(1,1) PRIMARY KEY,
[Name] VARCHAR(100) NOT NULL,
[Description] VARCHAR(200) NULL,
[Modified] DATETIME NOT NULL DEFAULT(GETUTCDATE()),
[ModifiedBy] VARCHAR(32) NOT NULL
);
INSERT INTO [dbo].[Product]([Name], [Description], [Modified], [ModifiedBy])
VALUES('Test', 'Description', GETUTCDATE(), 'Me');
Don't do anything just try to insert (' ')single quotes instead of (") quotes.. or if you insert data with ('')single quotes try for (") double quotes it's really helping you.

Dynamic Variable Name for backup table

I am trying to write a stored procedure to backup a table, but I keep getting:
Msg 402, Level 16, State 1, Line 9
The data types varchar and datetime2 are incompatible in the add operator.
Msg 402, Level 16, State 1, Line 15
The data types varchar and datetime2 are incompatible in the add operator.
How can I fix this?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
DECLARE #CreateDynamicSQL nvarchar(1000);
DECLARE #CopyDynamicSQL nvarchar(1000);
SET #CreateDynamicSQL='CREATE TABLE [dbo].[paul_AccountContact_Backup_'+#SYSDATETIME+'](
[AccountID] [int] NOT NULL,
[ContactID] [int] NOT NULL
) ON [PRIMARY]
GO'
SET #CopyDynamicSQL='select * into [dbo].[paul_AccountContact_Backup_'+#SYSDATETIME+'] from paul_AccountContacts'
EXEC(#CreateDynamicSQL);
EXEC(#CopyDynamicSQL);
You have to convert your date variable to a string so you can concatenate it:
SET #CreateDynamicSQL='CREATE TABLE [dbo].[paul_AccountContact_Backup_'
+ convert(varchar(20), #SYSDATETIME, <Format>) + '](
Documentation for the format parameter:
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-2017

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)

Got error while inserting Dataset into a database Table

This is the error
String or binary data would be truncated.
The data for table-valued parameter "#tblCustomers" doesn't conform to the table type of the parameter. SQL Server error is:
Msg 8152, state: 10
The statement has been terminated.
Here is the user-defined table type
CREATE TYPE [dbo].[recType] AS TABLE
(
[refid] [int] NULL,
[fromid] [varchar](13) NULL,
[toid] [varchar](13) NULL,
[message] [int] NULL,
[status] [varchar](13) NULL,
)
Here is the stored procedure
CREATE PROCEDURE [dbo].[SP_INSERT_RECVSMS]
#tblCustomers recType READONLY
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO RecieveSMS(Refid, fromID, Toid, message, status)
SELECT
refid, fromid, toid, message, status
FROM #tblCustomers
END
Error message is very clear. Target/source table column is to small to hold string value.
Change the size for string columns to appropriate values:
[fromid] [varchar](13) NULL
--
[fromid] [varchar](xxx) NULL,