How to rename a MSSQL Database that has name "Database"? - sql

I have a MSSQL Database named "Database". Now when I am trying to rename it using query shown below,
USE master;
GO
ALTER DATABASE Database
Modify Name = Database01
GO
It gives me this error message:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'Database'.
But this query works fine for other database. What I am doing wrong?

If you "quote" the table name it should work. The default quote characters are square brackets [], so:
USE master;
GO
ALTER DATABASE [Database]
Modify Name = Database01
GO

Instead of using the the Long code you Can just use the System built-in Stored Procedure -sp_renamedb'oldDBName','NewDBName'

when you have to use reserved keywords for table name,database name,column name always put [] (big brackets )
such as
select * from [Table] in place of select * from table
select [column] from [table] in place of select column from table
but its very bad idea to put reserved keyword as a name for your objects.

Related

postgres - where in (list) - column does not exist

I'm coming from SQL Server and I was suprised to see that the following query does not work:
DELETE FROM user_job_titles WHERE id IN (
"c836d018-1d12-4507-a268-a4d80d6d3f54",
"d0961a90-7d31-4c4c-9c1b-671115e3d833",
"62dda420-6e62-4017-b41d-205c0aa82ead"
)
where user_job_titles has the following columns:
id
user_id
job_title_id
The error is:
ERROR: column "c836d018-1d12-4507-a268-a4d80d6d3f54" does not exist
LINE 2: "c836d018-1d12-4507-a268-a4d80d6d3f54"
I'm using pgAdmin with latest postgresql version. Is there any other way to run this query?
Use single quotes for string constants:
DELETE FROM user_job_titles
WHERE id IN ('c836d018-1d12-4507-a268-a4d80d6d3f54',
'd0961a90-7d31-4c4c-9c1b-671115e3d833',
'62dda420-6e62-4017-b41d-205c0aa82ead'
);
Double quotes are an escape character used with table and column names. Hence the error.
You need to quote string literals with '
DELETE FROM user_job_titles
WHERE id IN (
'c836d018-1d12-4507-a268-a4d80d6d3f54',
'd0961a90-7d31-4c4c-9c1b-671115e3d833',
'62dda420-6e62-4017-b41d-205c0aa82ead'
);
I'm coming from SQL Server and I was suprised to see that the following query does not work
Then you have SET QUOTED_IDENTIFIER AS OFF. By default it is ON.
When SET QUOTED_IDENTIFIER is ON, all strings delimited by double
quotation marks are interpreted as object identifiers.
Check:
SET QUOTED_IDENTIFIER OFF;
SELECT "A"
-- The same behaviour as in Postgresql
SET QUOTED_IDENTIFIER ON;
SELECT "A"
-- Invalid column name 'A'.
LiveDemo

Setting a varchar column length with a variable or a subquery

I have a table that is created by an import of an Excel file. As is the case, all text fields are imported as nvarchar(255). I'd rather do the bulk import then manipulate the table afterwards. I know SSIS allows me to set data types and sizes via data mapping, but that doesn't seem to work consistently for me. Maybe I'm not holding my mouth right...
Anyway, I want to change the varchar length definitions to the max length of the data in each column. Rather than run a statement to check the max length as a literal...
select max(len(rtrim(FIELD))) from TABLE$
...I want to do it in code. So I hit on this idea:
declare #Var int
set #Var = (select max(len(rtrim(FIELD))) from TABLE$)
alter table dbo.TABLE$ alter column FIELD varchar(#Var)
Lines one and two work fine, but it gives me an error when executing the third line:
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near '#Var'.
So I tried this, thinking it would be a more compact solution...
alter table dbo.TABLE$
alter column FIELD varchar(select max(len(rtrim(FIELD))) from TABLE$)
...but it wasn't. I got these errors:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ')'.
So my question is kind of a two-parter. First, why won't these methods work, and second, what would work--short of finding the mas length of each column, then setting the varchar length with a literal?
Thanks in advance.
Dynamic SQL would work for what you're trying to do. Whether it's the right tool for the job or the right thing to do is another story. Give this a shot:
DECLARE #cmd NVARCHAR(4000)
SET #cmd = 'ALTER TABLE dbo.Table$ ALTER COLUMN FIELD VARCHAR(' + CAST((SELECT MAX(LEN(RTRIM(FIELD))) FROM dbo.TABLE$) AS NVARCHAR(10)) + ')'
EXEC(#cmd)
That query parses but I didn't try to run it. Be careful using Dynamic SQL though. It can get you into trouble if you start using it everywhere. Further reading:
http://sqlmag.com/database-performance-tuning/don-t-fear-dynamic-sql
http://www.sommarskog.se/dynamic_sql.html

How to escape ampersand in MS SQL

I have a table named tblCandy with an XML field named CandySpecs. When I try to add a value containing an ampersand (&) I get the error:
UPDATE tblCandy SET OrigOtherData.modify ('insert <BrandName>M&Ms</BrandName> as first into (CandySpecs/Table)[1]') WHERE RecordID = 1
Msg 2282, Level 16, State 1, Line 1
XQuery [tblCandy.CandySpecs.modify()]: Invalid entity reference
I’ve tried various escape sequences with no luck:
/&
\&
&&
There is a lot of guidance out there on this issue and I’m wondering if there is one best way to address this problem.
Here's a much better way to deal with this:
UPDATE tblCandy SET OrigOtherData.modify ('insert <BrandName><![CDATA[M&Ms]]></BrandName> as first into (CandySpecs/Table)[1]') WHERE RecordID = 1
Explanation: the CDATA tag tells the XML to ignore character markup for this block of data.
Related StackOverflow question (not strictly a dupe, but would be worth reading if you're not familiar with this): What does <![CDATA[]]> in XML mean?
This will bypass not only the &, but also other potentially breaking pieces of data such as < and > that could potentially exist within the data you're dealing with.
Special symbols in SQL server are being escaped with \
in your example statement would look following:
UPDATE tblCandy SET OrigOtherData.modify ('insert <BrandName>M\&Ms</BrandName> as first into (CandySpecs/Table)[1]') WHERE RecordID = 1
Using & instead of just &.
I found the answer on this article: http://www.techrepublic.com/article/beware-of-the-ampersand-when-using-xml/
SET NOCOUNT ON
GO
CREATE TABLE tblCandy ( Id INT, Brandname XML )
GO
INSERT INTO tblCandy VALUES ( 1, '<Brandname >test</Brandname >' )
GO
SELECT 'before', * FROM tblCandy
UPDATE tblCandy
SET Brandname.modify('replace value of (//Brandname/text())[1]
with string("as first into")')
WHERE Id = 1
SELECT 'After', * FROM tblCandy
GO
DROP TABLE tblCandy
GO

Calling Scalar-valued Functions in SQL

I have migrated a database from oracle, and now have a few Scalar-valued Functions.
However, when I call them, I get an error saying:
Cannot find either column "dbo" or the user-defined function or aggregate "dbo.chk_mgr", or the name is ambiguous.
I'm calling it like this:
SELECT dbo.chk_mgr('asdf')
What am I doing wrong?
Are you sure it's not a Table-Valued Function?
The reason I ask:
CREATE FUNCTION dbo.chk_mgr(#mgr VARCHAR(50))
RETURNS #mgr_table TABLE (mgr_name VARCHAR(50))
AS
BEGIN
INSERT #mgr_table (mgr_name) VALUES ('pointy haired boss')
RETURN
END
GO
SELECT dbo.chk_mgr('asdf')
GO
Result:
Msg 4121, Level 16, State 1, Line 1
Cannot find either column "dbo" or the user-defined function
or aggregate "dbo.chk_mgr", or the name is ambiguous.
However...
SELECT * FROM dbo.chk_mgr('asdf')
mgr_name
------------------
pointy haired boss
Can do the following
PRINT dbo.[FunctionName] ( [Parameter/Argument] )
E.g.:
PRINT dbo.StringSplit('77,54')
That syntax works fine for me:
CREATE FUNCTION dbo.test_func
(#in varchar(20))
RETURNS INT
AS
BEGIN
RETURN 1
END
GO
SELECT dbo.test_func('blah')
Are you sure that the function exists as a function and under the dbo schema?
You are using an inline table value function. Therefore you must use Select * From function.
If you want to use select function() you must use a scalar function.
https://msdn.microsoft.com/fr-fr/library/ms186755%28v=sql.120%29.aspx
Make sure you have the correct database selected. You may have the master database selected if you are trying to run it in a new query window.

is this a problem in the sp_rename function or sql server itself?

While renaming the column name, the square bracket is included in the column name, which I think is a bug,
Here is a sample code snippet,
create table [TestTable]
(TestColumnName nvarchar(30))
select TestColumnName from TestTable
sp_rename '[TestTable].[TestColumnName]', '[RenamedColumnName]', 'Column'
select [RenamedColumnName] from TestTable -- does not work "Invalid column name 'RenamedColumnName'."
select RenamedColumnName from TestTable -- does not work "Invalid column name 'RenamedColumnName'."
select * from [TestTable] -- works fine!!!
The bug here is that the column rename includes the square brackets, I found this which says that the "first character must be one of the following", but "[" does not seem be included in the list, is there a problem with sp_rename or sql server itself?, as it allows alteration of column name to start with a square bracket.
The column in your code has been renamed to one that actually includes [] - to query this column you'll have to use
SELECT [[RenamedColumnName]]] FROM TestTable
] is a delimited identifier, so you have to escape it. For ], this means an additional ] for each one used in the name.
If you want to fix this, you can do this:
IF EXISTS(SELECT * FROM sys.columns where name ='[MyColumn]' AND [object_id]=OBJECT_ID('[MyTable]'))
BEGIN
EXEC sp_rename 'MyTable.[[MyColumn]]]', 'MyColumn', 'COLUMN';
END
Don't ask me why it works, it just does.
Data error !!!
Its not
sp_rename '[TestTable].[TestColumnName]', '[RenamedColumnName]', 'Column'
It should be like this
sp_rename '[TestTable].[TestColumnName]', 'RenamedColumnName', 'Column'
then
select [RenamedColumnName] from TestTable -- works fine!!!
select RenamedColumnName from TestTable -- works fine!!!
select * from [TestTable] -- works fine!!!
Even though the new column name is with space like "Renamed ColumnName" NO NEED TO use the square brackets in the
It's not a bug, as "[" and "]" are valid characters within a column name. sp_rename has to work by receiving the exact column name you want to use - after all how would it know whether you wanted a column actually called "[MyColumnWithBrackets]" or "MyColumnWithBrackets". Hence, if you provide a name, it's treated literally and does not require you to manually enclose (e.g.) column names with spaces in, in brackets
the square brackets are used to mark the boundaries of the columns names. That way you can include reserved words, spaces, single quotes etc. in the column names and the script will not fail.
sp_rename: http://msdn.microsoft.com/en-us/library/aa238878(SQL.80).aspx
from BOL: This example renames the
contact title column in the customers
table to title: EXEC sp_rename
'customers.[contact title]', 'title',
'COLUMN'
try this:
sp_rename 'TestTable.TestColumnName', 'RenamedColumnName', 'Column'
since you are passing in strings into the procedure you don't need the square braces "[","]"
you can use "[","]" in the first parameter, but if you use them in the second parameter, they become part of the actual column name:
create table [TestTable2]([Test ColumnName] nvarchar(30))
exec sp_help testtable2
exec sp_rename 'dbo.TestTable2.[Test ColumnName]', 'Renamed ColumnName', 'Column'
exec sp_help testtable2