How do I link the File Table with my existing table in SQL server - sql

I have a requirement of saving employees image in database. I have been asked to use File Tables. After googling on this I got some fine contents as to how to get started with File Tables. And I managed to create them, also inserting data to these tables is as simple as copy/paste to specified folder and the data gets inserted into the table. The problem is how do I relate each employee row set with their respective images
The overall flow will be like the employee will upload his/her image or doc through front end, which will save the image on the server. the problem is how to add reference of employee with its respective image. One option can be having a FileName column in the employee table which refers to the name column in the FileTable, but I need something more efficient such as relating the id's. Any other way of achieving this would be appreciated.

First of it consumed a lot of time to get things right as filetable being a new feature introduced from SQLSERVER 2012 onwards. Secondly this is the approach I took to counter my issue. I will be providing some usefull links to make life easier for other developers. Hope it helps.
File table is almost similar to normal SQL tables, but has some configurations to be made to get it started, as it resides in a separate section of your database, inside tables-->FIleTables. Since the table structure is predefined, you cannot change the table schema. So the approach I took is to refer the stream_id as the reference key to link with the table that I want to use and handle the constrains logic through stored procedure. In my scenario the Employee table will have a stream_id column which will be linked to the File table via stream_id, also to make rows in the File table unique, I inserted the Employee Id as the name of the stored image and not the actual name of the file. With this even if anyone tries to insert the file directly by copy/paste it wouldn't have any relation with the Employee table, also you can provide access right to give desired permission. Check the links for more details. And that's it, with a little bit of tweaks I was able to solve my issue.
Below SQL scripts will be helpful to activate file stream at instance level at one shot.
EXEC sp_configure filestream_access_level, 2
RECONFIGURE
GO
--For new DB
CREATE DATABASE <DATABASE name>
WITH FILESTREAM
(
NON_TRANSACTED_ACCESS = FULL,
DIRECTORY_NAME = N'<DIRECTORY name>'
);
GO
--If you have an existing DB
ALTER DATABASE <DATABASE name>
ADD FILEGROUP <File group name>
CONTAINS FILESTREAM
GO
ALTER DATABASE <DATABASE name>
ADD FILE (NAME='<File group name>', FILENAME='<DIRECTORY name>')
TO FILEGROUP <File group name>
GO
ALTER DATABASE <DATABASE name>
SET FILESTREAM ( NON_TRANSACTED_ACCESS = FULL, DIRECTORY_NAME = N'<File
group name>')
GO
use <DATABASE name>
GO
CREATE TABLE <Filetable NAME> AS FileTable;
GO
Also some links which are very helpful:
https://www.mssqltips.com/sqlservertip/2667/filetable-feature-in-sql-server-2012/
http://sql-articles.com/articles/general/working-with-filetables/
https://michaelfirsov.wordpress.com/working-with-sql-server-file-tables-part-1/
https://michaelfirsov.wordpress.com/working-with-sql-server-file-tables-part-2/
https://msdn.microsoft.com/pl-pl/library/gg492084(v=sql.110).aspx
Thanks.

Wouldn't just having a "joining (many-to-many) table" in between employer and the filetable be just as easy? You wouldn't have to use it as a many-to-many table. Call it EmployeeImages and add a description attribute/property i.e "Hiring photo", "Just got fired photo". with both primary keys from employee and filetable. simples!

You have to insert in your program the code for copying file.
File.Copy(...) Instead of just copying and pasting into file system.
So that, each instance that your File.Copy executes, you can get its respective stream_id, which then you attach on your employees table..

Related

Deleting objects from SQL Server

In SQL Server Database Engine I have a table named Table A.
I deleted the table using graphical interface, but when I wanted to create a table with same name, the error shows
The object already exists
What is the remedy of this situation?
The following steps should help you track down what is going on and help you create your table:
Right-click on your database and select refresh
Verify that your table does not exist under this database.
If you table is
not shown here, then very likely your table is displayed under the
master database.
To create a table in your selected database,
first select the database and then run your query.
A better
option for number 4, just to be sure you are specifying the correct
database is to run the command use dbname; (where dbname is
the name of your database). Do this on the line above your create table code.

MSSQL Import/Export/Copy IDENTITY_INSERT problems

Using MS SQL Server Management Studio 2008.
I have a db (say ip 10.16.17.10 and called db1) and a second one (say ip 10.16.17.25 called db2).
I am trying to copy one table (and its contents) from db1 into db2.
I have the database on both (but empty in db2).
The problem is no matter how I copy/export/import, no matter what options I set in MS SQL Server Management Studio 2008 when I click 'table'->'Design' (on db2) it ALWAYS says 'Identity Spefication: NO' even tho the db1 table has it on.
From db1 I go to 'Tasks'->'export'->'source/db' and 'destination/db'->'Edit Mapping'->'Enable identity Insert' and click it on.
But no joy. ALWAYS exports without it.
I try similar thing from IMPORT on db2. Similar thing if I use COPY.
I have read MANY of the STACKOVERFLOW articles on this, they all suggest setting IDENTITY_INSERT setting to ON but when I do run below:
SET IDENTITY_INSERT [dbo].[mytable] ON
The table either doesn't exist yet or has already copied WITHOUT the identity setting on so see the error:
does not have the identity property. Cannot perform SET operation.
I have tried setting it as a property (under database properties) for db2 but when I copy/import/export never works.
Would appreciate any help here as lots of StackOverflow articles so far all seem to be having an easier time than me.
I am planning on doing this for another 50 or so tables in this database so am hoping to find a way which doesnt involve running scripts for each table.
thanks
The process of using the Export Data Wizard to copy the data from one table to another will NOT replicate all aspects of the schema (like identity and auto-increment). If you want to replicate the schema, script out your table into a create statement, change the name to db2, and create it. Then you should be able to run the export/import wizard with the identity insert option on and insert into your new table that replicates the schema of your old table.
Ended up sorting this out using MS SQL Management Studio.
Thanks to #kevin for the help regarding Import Data and Export Data. Schemas are NOT transferred across however they are the best means to transport the data once schema is up.
Found best way to MASS import/export db table schemas using below (Saved SQL create scripts to file):
Tasks->Generate Scripts->All Tables To File->with Identity on
Ran 200kb SQL file on db2 for schema.
Then ran Import Data from db1 to db2.
Done, all Identity_Inserts maintained.
thanks for help
According to the Error message I think your table does not have an IDENTITY column. Make sure that [dbo].[mytable] does have an IDENTITY column before you executing SET IDENTITY_INSERT.
SET IDENTITY_INSERT [dbo].[mytable] ON
DEMO1 (Trying to set identity ON when there is NO identity column)
--Error
'Table 'T' does not have the identity property. Cannot perform SET operation.: SET IDENTITY_INSERT T ON'
DEMO2 (Trying to set identity ON when there is identity column)
--No Errors
Follow following Steps :
From db1 I go to 'Tasks'->'export'->'source/db' and 'destination/db'->'Edit Mapping'->'Enable identity Insert' and Edit SQL - > You will able to see query structure of Table.
IN the query for eg. ID int NOT NULL, do the next step ID int NOT NULL IDENTITY(1,1)
Then proceed.
I bet it will work.

How to delete a large record from SQL Server?

In a database for a forum I mistakenly set the body to nvarchar(MAX). Well, someone posted the Encyclopedia Britanica, of course. So now there is a forum topic that won't load because of this one post. I have identified the post and ran a delete query on it but for some reason the query just sits and spins. I have let it go for a couple hours and it just sits there. Eventually it will time out.
I have tried editing the body of the post as well but that also sits and hangs. When I sit and let my query run the entire database hangs so I shut down the site in the mean time to prevent further requests while it does it's thinking. If I cancel my query then the site resumes as normal and all queries for records that don't involve the one in question work fantastically.
Has anyone else had this issue? Is there an easy way to smash this evil record to bits?
Update: Sorry, the version of SQL Server is 2008.
Here is the query I am running to delete the record:
DELETE FROM [u413].[replies] WHERE replyID=13461
I have also tried deleting the topic itself which has a relationship to replies and deletes on topics cascade to the related replies. This hangs as well.
Option 1. Depends on how big the table itself and how big are the rows.
Copy data to a new table:
SELECT *
INTO tempTable
FROM replies WITH (NOLOCK)
WHERE replyID != 13461
Although it will take time, table should not be locked during the copy process
Drop old table
DROP TABLE replies
Before you drop:
- script current indexes and triggers so you are able to recreate them later
- script and drop all the foreign keys to the table
Rename the new table
sp_rename 'tempTable', 'replies'
Recreate all the foreign keys, indexes and triggers.
Option 2. Partitioning.
Add a new bit column, called let's say 'Partition', set to 0 for all rows except the bad one. Set it to 1 for bad one.
Create partitioning function so there would be two partitions 0 and 1.
Create a temp table with the same structure as the original table.
Switch partition 1 from original table to the new temp table.
Drop temp table.
Remove partitioning from the source table and remove new column.
Partitioning topic is not simple. There are some examples in the internet, e.g. Partition switching in SQL Server 2005
Start by checking if your transaction is being blocked by another process. To do this, you can run this command..
SELECT * FROM sys.dm_os_waiting_tasks WHERE session_id = {spid}
Replace {spid} with the correct spid number of the connection running your DELETE command. To get that value, run SELECT ##spid before the DELETE command.
If the column sys.dm_os_waiting_tasks.blocking_session_id has a value, you can use activity monitor to see what that process is doing.
To open activity monitor, right-click on the server name in SSMS' Object Explorer and choose Activity Monitor. The Processes and Resource Waits sections are the ones you want.
Since you're having issues deleting the record and recreating the table, have you tried updating the record?
Something like (changing "body" field name to whatever it is in the table):
update [u413].[replies] set body='' WHERE replyID=13461
Once you clear out the text from that single reply record you should be able to alter the data type of the column to set an upper bound. Something like:
alter table [u413].[replies] alter column body nvarchar(100)

SQL drop table and re-create and keep data

On our original design we screwed up a foreign key constraint in our table. Now that the table is full of data we cannot change it without dropping all of the records in the table. The only solution I could think of is to create a backup table and put all of the records in there, then delete all the records, alter the table and start adding them back. Any other (BETTER) ideas? Thanks!
Using MS SQL Server
I'm a bit late, just for reference.
If You are using SQL Server Management Studio, You could generate a DROP and RECREATE script with "Keep schema and data" option.
Right click on the desired DB in object explorer
Tasks > Generate scripts
Select the table you want to script
Then clicking on Advanced button
"Script DROP and CREATE" ->"Script DROP and CREATE"
"Types of data to script" -> "Schema and data"
Hope this helps
Here's some pseudo-code. No need to make a backup table, just make a new table with the right constraint, insert your records into it, and rename.
CREATE TABLE MyTable_2
(...field definitions)
<add the constraint to MyTable_2>
INSERT INTO MyTable_2 (fields)
SELECT fields
FROM MyTable
DROP TABLE MyTable
exec sp_rename 'MyTable2', 'Mytable'
Using SQL Server Management Studio (SSMS), you can use it's table designer to specify the final condition of the table. Before saving the changes, have it generate the change script and save that script. Cancel out of the design window, open the script and review it. SSMS may already have generated a script that does everything you need, fixing the primary-foreign key relationship while preserving all existing data. If not, you will have a script, already started, that performs most of what you need to do and should be able to modify it for your needs.
This is your only solution.
Create the backup table, empty the original one, modify the table and then insert step-by-step until you find a violation.
Update All Schema Database Old by new Schema Database .
Create script (Right click on the desired DB in object explorer Tasks > Generate scripts -> select option select specific database objects and tables ->next -> advanced-> option Type of data to script Data only -> ok ->next ->next.) to data only and backup Database to old database
Drop database old and create new database and make new DB is empty .
Excute script of Old Data only on new database .

Persistent SQL Table lock from C#

I'm trying to create a persistent SQL (SQL Server 2005) lock on a table level. I'm not updating/querying the specified table, but I need to prevent a third party application from updating the locked table as a means to prevent transactions from being posted (the table I wish to lock is the key on their transaction that interferes with my processing).
From my experience the table is only locked for the time a specific transaction is taking place. Any ideas?
The 3rd party developer has logged this feature as an enhancement, but since they are in the middle of rolling out a major release I can expect to wait at least 6 months for this. I know that this isn't a great solution, since their software will fall over but it is of a critical enough nature that we're willing to live with the consequences.
Move the table to a different file group, then alter the file group to read-only. The table will be in effect read-only:
ALTER DATABASE dbName
ADD FILEGROUP ReadOnlyFG;
GO
ALTER DATABASE dbName
ADD FILE (
NAME = ...,
FILENAME = '...')
TO FILEGROUP ReadOnlyFG;
GO
ALTER TABLE tableName MOVE TO ReadOnlyFG;
GO
ALTER DATABASE dbName
MODIFY FILEGROUP ReadOnlyFG READONLY;
rename the table and when the 3rd party is ready rename it back to what it should be