SQL Server : add CSV programmable - sql

I have the following code to insert a CSV file into a temp table:
USE [websitehere.com].[dbo]
GO
CREATE TABLE [websitehere.com].[dbo].[tmpTable]
(ID INT,
Caller_Number VARCHAR(100),
Caller_Name VARCHAR(100),
GroupBy VARCHAR(100),
Campaign_Name VARCHAR(100),
DateAndTime VARCHAR(100),
Duration VARCHAR(100),
Call_Status VARCHAR(100))
GO;
BULK
INSERT tmpTable
FROM 'C:\Users\namehere\Documents\CallLog.csv'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
GO
But...
It does not seem to add the tmpTable. It gives me an error
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'.
It won't add the insert command saying that
Msg 4834, Level 16, State 4, Line 8
You do not have permission to use the bulk load statement.
Any help would be great to take care of these 2 errors!
Update

The line
USE [websitehere.com].[dbo]
should say
USE [websitehere.com]
The second error should be fixed by assigning the propper permissions or role memeberships for your user. You need INSERT and ADMINISTER BULK OPERATIONS permissions. Maybe more, depending on what other options your bulk insert statement might have.
You might want to try this with some test user account:
USE master;
GO
CREATE LOGIN bulkuser WITH PASSWORD = 'P#ssw0rd';
GRANT ADMINISTER BULK OPERATIONS to bulkuser;
USE [websitehere.com]
GO
CREATE USER bulkuser FOR LOGIN bulkuser;
EXEC sp_addrolemember 'db_datareader', 'bulkuser'
GRANT INSERT ON [dbo].[tmpTable] TO bulkuser;
Then login as "bulkuser" and try running your BULK INSERT statement.

Ah found where i needed to grant access to be able to use it!
Right-click on your database table >
properties >
select Permissions from the left panel >
click the blue link "View server permissions" >
check "Grant" for "Administer bulk operations" >
Ok > Ok > Done!

Related

Insert return records from stored procedure - SQL

The script below return a select records:
EXEC [LINK_SERV].[DB_SAMPLE].[dbo].[SP_SAMPLE] '1235123'
The I want to insert the return records to a temp table so I wrote the script below (assumed temp table is already created):
INSERT INTO #TempTable
EXEC [LINK_SERV].[DB_SAMPLE].[dbo].[SP_SAMPLE] '1235123'
But I get this error:
OLE DB provider "SQLNCLI11" for linked server "LINK_SERV" returned message "The partner transaction manager has disabled its support for remote/network transactions.
Msg 7391, Level 16, State 2, Line 25
The operation could not be performed because OLE DB provider "SQLNCLI11" for linked server "LINK_SERV" was unable to begin a distributed transaction.
Please advise the specific config to enable this. I tried the same code in some other server and it work. Thank you in advance.
This is where the beauty of OPENQUERY() comes into great use.
i.e. something like this...
INSERT INTO dbo.MyTable2
SELECT Col1, Col2, etc
FROM dbo.MyTable1
LEFT JOIN OPENQUERY(<<LINKEDSERVER>>,
'SELECT BLAHBLAH
FROM dbo.BLAHBLAH WHERE <something> = <something>);

can I give SQL Server database name with hyphen like abc-123?

I created a sql server database with name of abc-123, in that I created a table Emp, when I run likeselect * from abc-123.emp; I am getting the results.
But when I am trying to grant some privilege to the user I unable to do that, getting syntax error near hyphen .
will any one help me?
Make sure you are escaping the names with [] (T-SQL) or "" (ANSI SQL). You are using non-standard naming.
-- Sample select
SELECT * FROM [abc-123].[dbo].[emp];
SELECT * FROM "abc-123"."dbo"."emp";
1 - Can you send me an example of the grant TSQL? If you are doing the action from SSMS, right click and script the code.
2 - Here is the link to the GRANT TSQL command. I do not see any syntax like you are trying.
http://technet.microsoft.com/en-us/library/ms188371.aspx
TO 'drupal'#'localhost' IDENTIFIED BY 'Drup#l';
First, it should be [drupal#localhost]. Second, I never seen the IDENTIFIED BY clause. Where are you getting that information from?
3 - Here is a quick TSQL script that creates a badly named database and user. If possible, change the name of the database and user.
Also, if you are granting permissions at the table level other than db_owner (very granular and a-lot of maintenance), then create an user defined database role. Add securables to the role and add your user to the role.
http://technet.microsoft.com/en-us/library/ms187936.aspx
Sample code.
-- Create new database
create database [abc-123]
go
-- Use new database
use [abc-123];
go
-- Create table from sample data
select
[BusinessEntityID]
,[PersonType]
,[NameStyle]
,[Title]
,[FirstName]
,[MiddleName]
,[LastName]
,[Suffix]
,[EmailPromotion]
, cast([AdditionalContactInfo] as varchar(max))
as [AdditionalContactInfoTxt]
, cast([Demographics] as varchar(max))
as [DemographicsTxt]
,[rowguid]
,[ModifiedDate]
into
[abc-123].[dbo].[emp]
from
AdventureWorks2012.Person.Person;
-- Create a login
CREATE LOGIN [drupal#localhost] WITH PASSWORD=N'Ja08n13$', DEFAULT_DATABASE=[abc-123]
GO
-- Create a user
CREATE USER [drupal#localhost] FOR LOGIN [drupal#localhost] WITH DEFAULT_SCHEMA=[dbo]
GO
-- Add to database owner role
EXEC sp_addrolemember 'db_owner', [drupal#localhost]
GO
Output with user in db_owner group.
Use Back Quote for the DB name
select * from `abc-123`.emp;
or, select the existing database with a USE statement and run the query.
USE `abc-123`;
select * from emp;
Use [] round the database name:
SELECT * FROM [abc-123].[dbo].emp;
OR
SELECT * FROM [abc-123].dbo.emp;
if you are using databasename with table name then suppose to specify the schema name also.select * from [abc-123].dbo.emp

Database creation in master

Now here is the query am trying to run to execute a script that will build up my database according to the script:
USE master
GO
if exists (select * from sysdatabases where name='Northwind')
drop database Northwind
go
DECLARE #device_directory NVARCHAR(520)
SELECT #device_directory = SUBSTRING(filename, 1, CHARINDEX(N'master.mdf', LOWER(filename)) - 1)
FROM master.dbo.sysaltfiles WHERE dbid = 1 AND fileid = 1
EXECUTE (N'CREATE DATABASE Northwind
ON PRIMARY (NAME = N''Northwind'', FILENAME = N''' + #device_directory + N'northwnd.mdf'')
LOG ON (NAME = N''Northwind_log'', FILENAME = N''' + #device_directory + N'northwnd.ldf'')')
go
exec sp_dboption 'Northwind','trunc. log on chkpt.','true'
exec sp_dboption 'Northwind','select into/bulkcopy','true'
GO
Now here is the error am getting...
Msg 262, Level 14, State 1, Line 1
CREATE DATABASE permission denied in database 'master'.
Msg 15010, Level 16, State 1, Procedure sp_dboption, Line 64
The database 'Northwind' does not exist. Supply a valid database name. To see available databases, use sys.databases.
Msg 15010, Level 16, State 1, Procedure sp_dboption, Line 64
The database 'Northwind' does not exist. Supply a valid database name. To see available databases, use sys.databases.
Kindly help! The database should be made now in master but its not!
Your should have CREATE DATABASE permission to create new datebase. If you are not familiar with this topic, try to login as "sa" user (if you know password), or ask administrator to add your login to "sysadmin" role at SQL Server.

Avoid alter and drop command on a Table and SP in SQL Server

I have a table and a SP in SQL Server. I want to add Permissions on a table and SP that no one can change the Structure of table and Logic of SP. Is there any way to specify such type of Permissions. Any Trigger which avoids drop and alter commands, or any other way to do this.
Thanks in Advance.
You need to create and use a separate user that has only privileges that you explicitly allow it to (eg GRANT SELECT from table or GRANT EXECUTE on your stored procedure).
Rather than looking at it as disallowing certain actions you should consider what actions are allowed (see Principle of Least Privilege).
It is highly recommended that you manage the permissions on the objects. However, if you have no control over the permissions, consider setting up a database DDL trigger to at least log the events.
create table AuditTable
(
event_type varchar(max) not null
, tsql_command varchar(max) not null
, modified_by varchar(128) not null default (current_user)
, modified_time datetime not null default (getdate())
)
go
create trigger log_database_level_event
on database
for ddl_database_level_events
as
insert AuditTable
(
event_type
, tsql_command
)
values
(
eventdata().value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(max)')
, eventdata().value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'varchar(max)')
)
go
create user tester without login
go
execute as user = 'tester'
go
create proc test_proc
as
select ##version
go
alter proc test_proc
as
select 1
go
revert
go
select * from AuditTable
go
Yes, this is possible but not using constraint . Constraint is a bussiness rule kind of validation and here your question about Permission on Objects so now
this is clear that you need to define permission on object for specific user.If you want to
secure your Table and Stored Procedure then please follow this step.
Create one new User/Login with specific Database/Objects permission.
Give grant on your Secure table using - GRANT SELECT ON <TableName> TO <Username>
GIVE grant on your Secure Stored Procedure using - GRANT EXECUTE ON <SP Name> TO <Username>
for further regarding permission please do some search on Google .

How to deny delete on a table for all users

Within SQL Server 2005, is there a way, with a single statement, to deny delete on rows
in a particular table for all users of the database?
try this:
CREATE TRIGGER yourTriggerName ON YourTableName
INSTEAD OF DELETE
AS
ROLLBACK
RAISERROR('ERROR, DELETEs not permitted in YourTableName!!!',16,1)
RETURN
go
working sample:
CREATE TABLE XYZ (RowID int)
INSERT XYZ VALUES(1)
INSERT XYZ VALUES(2)
go
CREATE TRIGGER yourTriggerName ON XYZ
INSTEAD OF DELETE
AS
ROLLBACK
RAISERROR('ERROR, DELETEs not permitted in XYZ!!!',16,1)
RETURN
go
delete XYZ
OUTPUT:
Msg 50000, Level 16, State 1, Procedure yourTriggerName, Line 6
ERROR, DELETEs not permitted in XYZ!!!
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.
Kind of extreme, but you can look at an INSTEAD OF DELETE trigger to ignore the deletions. You could raise an error similar to 'delete access ... denied'
Obviously users with db_owner access privileges could drop the trigger
if you want to row based restriction create a table (for lock) and insert ids of rows that you want to protect. and create a relation.
Only triggers (or refactor your security/permission model)
One example where permissions won't help: If you have stored procs that delete rows, and both the proc/table have the same owner, table permissions will not be checked, even DENY. See ownership chaining. So users can delete or change data without any rights on the table at all.