SQL Server: how to create temp table with auto increment? - sql

I am trying to create a temp table with an auto increment and insert data. The table is created correctly, but I cannot import the data.
If I just omit the ID table it works correctly, but I need to have the temp table have an ID that we can reference.
The errors I get are:
Msg 4832, Level 16, State 1, Line 1
Bulk load: An unexpected end of file was encountered in the data file.
Msg 7399, Level 16, State 1, Line 1
The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error.
My code:
SET #strFileName = 'file.txt';
SET NOCOUNT OFF;
CREATE TABLE #UUID
(
id INT NOT NULL IDENTITY PRIMARY KEY,
cuuid NVARCHAR(50) COLLATE DATABASE_DEFAULT NULL
);
SET #strSQL = 'BULK INSERT #UUIDFROM ''' + #strFileName + ''' WITH (ROWTERMINATOR =''\n'' )';
EXEC #intErr = sp_executesql #strSQL;
I wonder if it's trying to insert into the the id row instead of the cuuid row...
Any ideas?

If the problem is that you have an extra column in the database that is not in the data file, then the solution is a view. Alas, I don't think you can do this with a temp table.
With a regular table:
CREATE TABLE temp_UUID (
id INT NOT NULL IDENTITY PRIMARY KEY,
cuuid NVARCHAR(50) COLLATE DATABASE_DEFAULT NULL
);
CREATE VIEW temp_UUID_v as
SELECT cuuid
FROM temp_UUID;
SET #strSQL = 'BULK INSERT temp_UUID_V FROM ''' + #strFileName + ''' WITH ( ROWTERMINATOR =''\n'' )';
EXEC #intErr= sp_executesql #strSQL;

Related

Mssql: insert into table with dynamic name in variable

I'm working with dynamic table name in variable, as example
#tableName varchar(512) = master.dbo.TableName'
I can work with it in dynamic code, like that:
DECLARE #sqlCode varchar(max) = CONCAT('
CREATE TABLE ',#tableName,(
Id Integer identity (1,1) not null,
Name varchar(512) not null
);
';
EXEC (#sqlCode);
I can insert data only in dynamic code or another way?

How to properly create an insert trigger with SQL Server

I am trying to create a trigger to send INSERT information from base table (Hub) to a log table.
The Log table contains the following columns:
ChangeID, Date, User, Table, Action, Description
The Hub table has 3 columns:
Date, Mat, Hub
I'm using this T-SQL code for my trigger:
CREATE TRIGGER tg_test
ON Hub
FOR INSERT
AS
BEGIN
DECLARE #sys_usr CHAR(30);
SET #sys_usr = SYSTEM_USER;
SET NOCOUNT ON;
INSERT INTO Logs_Table (Date, User, Table, Action, Description)
SELECT
(CURRENT_TIMESTAMP,
SYSTEM_USER,
'Hub',
'INSERT',
CONCAT('Mat: ', i.Mat, '; Hub: ', i.Hub))
FROM
INSERTED AS i;
The Logs_Table was created with following SQL:
CREATE TABLE Logs_Table
(
ChangeID INT IDENTITY PRIMARY KEY,
Date DATETIME,
User VARCHAR(200),
Table VARCHAR(200),
Action VARCHAR(100),
Description VARCHAR(MAX)
)
When I try to run the command to execute the query to create the trigger I get the following error:
ProgrammingError: (102, Incorrect syntax near ','.
DB-Lib error message 20018, severity 15:
General SQL Server error: Check messages from the SQL Server
Does anybody know where that syntax error is?
You shouldn't have ( and ) around the list of columns in your SELECT.
INSERT dbo.Logs_Table([Date], [User], [Table], Action, Description)
SELECT -- remove this (
CURRENT_TIMESTAMP,
SYSTEM_USER,
'Hub',
'INSERT',
CONCAT('Mat: ', i.Mat, '; Hub: ', i.Hub) -- remove this )
FROM INSERTED AS i;
Next, your trigger has a BEGIN but seems to be missing an END.
You should also try to avoid using generic and reserved words like Date, User, and Table for column names, and always use schema prefix. It also might make sense to apply defaults to the columns in the log table that take built-in functions, so you don't have to reference them in the trigger at all.
CREATE TABLE dbo.Logs_Table
(
ChangeID INT IDENTITY PRIMARY KEY,
[Date] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
[User] VARCHAR(200) NOT NULL DEFAULT SYSTEM_USER,
[Table] VARCHAR(200),
Action VARCHAR(100),
Description VARCHAR(MAX)
);
This really simplifies the insert in your trigger. A couple of other comments, [User] and [Table] should really be nvarchar, and I was lazy but default constraints should be named.

I need to create a SQL table using dynamic SQL

I am trying to write a stored procedure in SSMS that creates a table, along with two columns with the subject of the table as the single parameter. The table must be named t followed by the subject of the table. As for the columns, the first column is an auto-incrementing surrogate key ID field (and the primary key) that is named as the subject of the table, followed by ID.
The second column is a natural key which is named as the subject of the table. For instance, a table to be created with the subject being Student would create a table named tStudent, with a StudentID surrogate key column as well as a natural key column named Student. I am trying to do this using a dynamic SQL statement (which I am new to) and keep running into issues while trying to implement my natural key column.
ALTER PROC spCreateTable
#subjectOfTable varchar(50)
AS
DECLARE #dynamicSQL nvarchar(500),
#tableName varchar(50),
#tableID varchar(50);
SET #tableName = ('t' + #subjectOfTable);
SET #tableID = (#subjectOfTable + 'ID');
SET #dynamicSQL = 'CREATE TABLE ' + #tableName + ' ( '+ #tableID + ' INT NOT NULL PRIMARY KEY IDENTITY(1,1) ' + #subjectOfTable + ' VARCHAR(50) ) ';
EXEC (#dynamicSQL)
GO
I can get it to work correctly while just adding the tableID column, but keep having syntax issues with the natural key column subjectOfTable. Someone please help!

how to delete a primary key which is having auto increment [duplicate]

This question already has answers here:
Finding a Primary Key Constraint on the fly in SQL Server 2005
(4 answers)
Closed 5 years ago.
I need to drop the primary key of a table Student in a SQL Server database.
I have edited in the table and the script I got is
ALTER TABLE dbo.Student
DROP CONSTRAINT PK__Student__9CC368536561EF8B
But when I run this script in SQL Server query browser to drop the primary key
It shows the message
Msg 3728, Level 16, State 1, Line 1
'PK__Student__9CC368536561EF8B' is not a constraint.
Msg 3727, Level 16, State 0, Line 1
To my concern I think PK__Student__9CC368536561EF8B this will be generated randomly
please help me to drop the primary key constraint using script.
Thanks in advance
You can look up the constraint name in the sys.key_constraints table:
SELECT name
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = Object_id('dbo.Student');
If you don't care about the name, but simply want to drop it, you can use a combination of this and dynamic sql:
DECLARE #table NVARCHAR(512), #sql NVARCHAR(MAX);
SELECT #table = N'dbo.Student';
SELECT #sql = 'ALTER TABLE ' + #table
+ ' DROP CONSTRAINT ' + name + ';'
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = OBJECT_ID(#table);
EXEC sp_executeSQL #sql;
This code is from Aaron Bertrand (source).
simply click
'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'
and run the below query is :
Query:alter Table 'TableName' drop constraint PK__TableName__30242045
The answer I got is that variables and subqueries
will not work and we have to user dynamic SQL script. The following works:
DECLARE #SQL VARCHAR(4000)
SET #SQL = 'ALTER TABLE dbo.Student DROP CONSTRAINT |ConstraintName| '
SET #SQL = REPLACE(#SQL, '|ConstraintName|', ( SELECT name
FROM sysobjects
WHERE xtype = 'PK'
AND parent_obj = OBJECT_ID('Student')))
EXEC (#SQL)

A stored proc to copy table data including any default value or binding data via a SQL script running within SQL Server

I would like to be able to copy a table and it's data and also still have any default value or binding (as it is labelled within SQL Server Management console) constraints copied over.
The script below is a testing script to demonstrate the idea. The last line I assume needs to be replaced with a call to a custom stored proc?
Note: The source table (aSourceTbl) schema varies and can change over time.
--TEST SETUP
--Delete the prev tables so test script can be replayed
IF OBJECT_ID('aSourceTbl', 'U') IS NOT NULL
DROP TABLE aSourceTbl;
IF OBJECT_ID('aSourceCopyTbl', 'U') IS NOT NULL
DROP TABLE aSourceCopyTbl;
--Simple table to demonstrate table copying does not carry over the table constraits
CREATE TABLE [dbo].[aSourceTbl](
[aValue] [int] NOT NULL,
[DELETED] [int] NOT NULL
) ON [PRIMARY]
--Add some dummy data
INSERT INTO aSourceTbl (aValue, DELETED) VALUES (1,2);
INSERT INTO aSourceTbl (aValue, DELETED) VALUES (3,4);
--Add constraints of default values of 0 in this case
ALTER TABLE [dbo].[aSourceTbl] ADD CONSTRAINT [DF_aSourceTbl_aValue] DEFAULT ((0)) FOR [aValue]
ALTER TABLE [dbo].[aSourceTbl] ADD CONSTRAINT [DF_aSourceTbl_DELETED] DEFAULT ((0)) FOR [DELETED]
--Actual Required SQL script from here down
--The line below works nicely but does not copy the 2 constraints from the lines above into the new table.
--TODO QUESTION: Replace line below with the same functionaility + the constraints are also copied into new table
Select * INTO aSourceCopyTbl FROM aSourceTbl
Could you please help me by suggesting a suitable stored proc that can replace the last line in above SQL snippet? Any help greatly appreciated :)
References:
Similar SO Question however focuses on PK constraints. I am only interested in default value constraints in this case.
You can execute this code after the last row which will replicate the defauld constraints to the new table (replace the variables with your table names).
declare #table_name sysname, #new_table sysname, #cmd varchar(max)
select #table_name = 'SOURCE_TABLE', #cmd = '', #new_table = 'TEST_TABLE'
select #cmd = #cmd+'ALTER TABLE '+#new_table+' ADD CONSTRAINT [DF_' +#new_table+'_'+a.name+'] DEFAULT '+b.definition+' FOR['+a.name+'];
'
from sys.columns a
join sys.default_constraints b on a.object_id = b.parent_object_id and a.column_id = b.parent_column_id
where a.object_id = object_id(#table_name)
print #cmd
exec (#cmd)