How to escape square brackets inside a SP parameter - sql-server

I'm trying to use the stored procedure sp_rename to change column names. However, I get errors when trying to reference the columns because they contain the symbols [ and ]. I can't even to a select:
select [Materials].[All] from Temp_Table
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "Materials.All" could not be bound.
"[Materials].[All]" is the name of the column. I've tried it like this:
select "[Materials].[All]" from Temp_Table
select [[Materials].[All]] from Temp_Table
Do you see any solutions? Thanks.
EDIT: Ok, some solutions have been presented to make it work in a select statement, but I still get an error when using it in the stored procedure:
EXEC sp_rename '[DBName].[Temp_Table].[Materials].[Material Type].[All]]', 'All', 'COLUMN';
Error: Syntax error parsing SQL identifier '[KS_Control_Area].[Temp_Table_MaterialType_Mios].[Materials].[Material Type].[All]]'.

You need to quote you column's name correctly. So, for a column named silly[column]name you would use [silly[column]]name]. Note that the [ inside the name doesn't need be escaped, however the ] does (to ]]).

Related

How can I use a where statement in my procedure with open quotes inside the select statement already?

In my procedure, I need to have input parameters for the table and I need to be able to make multiple select statements into my procedure. However when I begun to add WHERE conditions, they only worked on numerical conditions i.e. where number = 1, but it doesn't work for text = 'a' as the statement already opens with ' ' i.e. 'select...' (see the code)
So the text conditions conflicts with the opening quote mark.
So how do I add this where statement with regards to text?
(The problem is where date is)
The output is the following:
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near '00'.
(53 rows affected)
I've tried to separate the where clause with separate ' ' but no use.
I've tried to use " inside the ' ' but no use, and says 'column name not recognised'
I've tried to treat the text as numeric without ' ' but no use.
CREATE PROCEDURE AllRowsAndCount35
    #table1 NVARCHAR(128)
AS
BEGIN
    DECLARE #SafeTableName AS NVARCHAR(128)
    SELECT #SafeTableName = QUOTENAME(TABLE_NAME)
    FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_NAME = #table1
    DECLARE #sql AS NVARCHAR(MAX) = 'select count(*) as countrows from ' + #SafeTableName + 'where valid_from_etl = 2019-06-24 00:00:00.000'
    EXEC(#SQL)
DECLARE #sql2 AS NVARCHAR(MAX) = 'select * from ' + #SafeTableName
    EXEC(#SQL2)
END
EXEC AllRowsAndCount35 'Dim_Cluster'
I would like a result showing a count of rows, another separate result showing the entire table
Basically two separate queries based off the procedure where I enter the table name as an input parameter
Instead the error message is:
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near '00'.
Use two single quotes (not a double quote) to represent a single quote inside a quoted string.
For example: 'SELECT... WHERE date = ''date'''
Or better yet, use a variable like you are for #safetablename.
That all said, your proc won't return both data sets. You'll have to use a UNION to make 1 final select with all the data you want returned, or use parameters to define which query is executed when the proc is called and call the proc twice, or make two separate procs.

Copy one table data into another db by using INTO Select

I am getting this error :
Msg 156, Level 15, State 1, Line 39
Incorrect syntax near the keyword 'in'
My code:
SELECT *
INTO EmployeesBackup IN 'DB2.mbd'
FROM Employee
Your syntax is off, and perhaps you intended to do an INSERT INTO ... SELECT:
INSERT INTO DB2.EmployeesBackup
SELECT *
FROM DB1.Employee;
This would work assuming that both databases are on the same server, and that your backup table EmployeesBackup has the same definition as the Employee table.
Try this:
INSERT INTO [DBName].dbo.EmployeesBackup
SELECT * FROM [DBName].dbo.Employee
Please note that, Either both database should be available on the same SQL Server OR if one of them is available on the different server then it should be Linked

MS SQL server 2005 - Error while querying with a column name as key

I have a table with a column name as "key". I am unable to filter based on that column
select * from myTable where key='someVal'
I get the following error
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'key'.
I cannot change the column name. How I can circumvent this issue?
It's because key is a keyword. If you have keywords as object names, you need to put them in brackets:
select * from myTable where [key]='someVal'

cannot add new column (Incorrect syntax near the keyword 'COLUMN')

When I run this
ALTER TABLE agency
ADD COLUMN single_word varchar(100)
I get
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'COLUMN'.
I tried removing the COLUMN but still same problem.
For TSQL Flavor try this syntax:
ALTER TABLE agents
ADD [associated department] varchar(100)
I have same issue when running that query on HeidiSQL. The solution is simple, change the query to be like this:
ALTER TABLE "agency"
ADD "single_word" varchar(100)
just remove "COLUMN" keyword.
Depending on the database software you are using, if you want to have a space in the column name (which I would recommend against), you will have to escape it.
For example, in MySQL, you would use the backtick (the character to the left of the number 1 at the top of the keyboard) :
ALTER TABLE agents
ADD COLUMN `associated department` varchar(100);
For SQL Server, you can use [], and for most other DBMSes, the double-quote (") will escape identifiers

Sql Stored Procedures

I'm trying to write a Stored Procedure this is what I have so far
Create procedure sp_Create_order
#P_nafn varchar(50),
#P_fj int,
#P_sótt datetime,
#F_kt varchar(10),
#V_nr int,
#L_id int
as
begin
set nocount on
if exists(
   select * from Lotur
   where L_id=#L_id and
   #P_sótt between L_hefst and L_pfrest
)
INSERT INTO Pantar(P_nafn, P_fj, P_sótt, F_kt, V_nr, L_id)
VALUES (#P_nafn, #P_fj, #P_sótt, #F_kt, #V_nr, #L_id)
end
but I am getting these errors
Msg 102, Level 15, State 1, Procedure
sp_Create_order, Line 14 Incorrect
syntax near ' '.
Msg 102, Level 15, State 1, Procedure
sp_Create_order, Line 15 Incorrect
syntax near ' '.
on these lines
select * from Lotur
where L_id=#L_id
and
#P_sótt, L_hefst and L_pfrest
are all dates and I am tryng to put a condition on saying that nothing should be Inserted unless #P_sótt is equal to or between L_hefst and L_pfrest
Please use meaningful names for your variables
Do not create sp for every thing like the one above
Modify the query to have SELECT L_ID NOT SELECT *
As for the error, probably you have mistyped something
First of all, I wouldn't recommend prefixing your Stored Procedure with sp_. Performance is at least one reason why it's a bad idea.
Your stored procedure compiled ok for me. Another recommendation would be to use
if exists (
select 1
from
Lotur
where
L_id= #L_id
and #P_sótt between L_hefst and L_pfrest
)
as opposed to SELECT *. Did you get the error when compiling or trying to use it?
EDIT:
In response to your post about raising errors, you might want to look at RAISERROR. Here is an example of how to use it in Stored procedures

Resources