I have created a stored procedure which creates a table at runtime. The table columns and their data types for this dynamic table comes from another table already in place in database.
I am calling this stored procedure from C# console application code. The stored procedure is throwing a syntax error and I am totally not able to figure out what is causing this syntax error.
This is the stored procedure code I've written:
CREATE procedure [dbo].[sproc_TableExists]
#TableName NVARCHAR(128)
,#Column1Name NVARCHAR(32)
,#Column1DataType NVARCHAR(32)
,#Column1Nullable NVARCHAR(32)
AS
DECLARE #SQLString NVARCHAR(MAX)
BEGIN
IF( EXISTS (select * from INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = #TableName))
BEGIN
SET #SQLString = 'ALTER TABLE ' + #TableName + '( '+ #Column1Name + ' ' + #Column1DataType + ' '+ #Column1Nullable +')'
EXEC (#SQLString)
END
ELSE
BEGIN
SET #SQLString = 'CREATE TABLE ' + #TableName + '( '+ #Column1Name + ' ' + #Column1DataType + ' '+ #Column1Nullable +')'
EXEC (#SQLString)
END
END
GO
Error I am getting calling it from code :
Incorrect syntax near '('.
The problem lies in the following line of code, when altering an existing table:
SET #SQLString = 'ALTER TABLE ' + #TableName + '( '+ #Column1Name + ' ' + #Column1DataType + ' '+ #Column1Nullable +')'
This generates the following output (as an example using a fake table\column name):
ALTER TABLE TableEx( ColumnEx NVARCHAR(MAX) NULL)
However, this is not a valid SQL statement.
If you want the behaviour to be to add a new column when the table already exists, use this instead:
SET #SQLString = 'ALTER TABLE ' + #TableName + ' ADD '+ #Column1Name + ' ' + #Column1DataType + ' '+ #Column1Nullable
Which will produce the output:
ALTER TABLE TableEx ADD ColumnEx NVARCHAR(MAX) NULL
Note that if your intention is to change the name of a pre-existing column in a pre-existing table you will need to test for this separately - the above only adds a new column to an existing table.
Replace
EXEC (#SQLString)
with
EXEC #SQLString
Related
I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END
I have problem, I'm having trouble viewing user information using stored procedure. The procedure accepts three parameters: table, column and searchBySomething. Every time I want to search for a user using another column, the column variable receives the column of the id and the searchBySomething variable receives specific id, the procedure is work but when I'm send another column I'm get the error message
Invalid column name (the data)
The procedure looks like this :
ALTER PROCEDURE [dbo].[userDetailsDisplay]
#table NVARCHAR(30),
#column NVARCHAR(30),
#searchBySomething NVARCHAR(30)
DECLARE #sql NVARCHAR(100)
SET #sql = 'SELECT * FROM ' + #table + ' WHERE ' + #column + ' = ' + #searchBySomething
EXECUTE sp_executesql #sql
So the specific error you're getting is because you're not checking the input to see if the string being passed into #column actually exists. You can check for it's existence against the metadata catalog view sys.columns doing something like this:
if not exists
(
select 1
from sys.columns
where object_id = object_id(#table)
and name = #column
)
begin
raiserror('Column %s does not exist in table %t', 16, 1, #column, #table)
return
end
However I would be remiss if I didn't point out two things.
First, this dynamic table dynamic where clause pattern is very bad practice. If it's for someone who already has database access, they can simply query the tables themselves. And if it's for an external user, well, you've basically given them full database read access through this procedure. Of course there are some rare occasions where this pattern is needed, so if you're dead set on using dynamic sql, that leads me to my next point.
The code you've written is vulnerable to a SQL injection attack. Any time you use dynamic SQL you must be VERY careful how it's constructed. Say I passed in the column name ; drop database [admin]-- Assuming you had such a database, my could would happily be executed and your database would disappear.
How to make dynamic SQL safe is a complex topic, but if you're serious about learning more about it, this is probably one of the best articles you can find. http://www.sommarskog.se/dynamic_sql.html
By parameterizing your query and using quotename() on the table and column, I modified it to look like this. This will still throw weird errors if someone tries to do an injection attack, but at least it wont actually execute their code.
create procedure [dbo].[userDetailsDisplay]
#table nvarchar(30),
#column nvarchar(30),
#searchBySomething nvarchar(30)
as
begin
declare
#sql nvarchar(max),
#params nvarchar(1000)
if not exists
(
select 1
from sys.columns
where object_id = object_id(#table)
and name = #column
)
begin
raiserror('Column %s does not exist in table %t', 16, 1, #column, #table)
return
end
select #sql = '
select *
from ' + quotename(#table) + ' WHERE ' + quotename(#column) + ' = #searchBySomething'
execute sp_executesql
#stmt = #sql,
#params = '#searchBySomething nvarchar(30)',
#searchBySomething = #searchBySomething
end
Just check to make sure that the column exist in the table.
for each #table called, check that the #column variable is in that table.
SET #sql = 'SELECT * FROM ' + #table + ' WHERE ' + #column + ' = ' +''' #searchBySomething +''''
Ex : select * from table where column ='value'
I want to create a new table with existing table, where the table names should to pass from input parameters.
I am trying the following code.
DECLARE #oldTableName nvarchar(50)
DECLARE #newStagingTableName nvarchar(50)
SET #oldTableName='OldTableName'
SET #newStagingTableName ='NewTableName';
SELECT * INTO #newStagingTableName FROM #oldTableName WHERE 1 = 0;
The SQL server is giving error while parsing this query.
Could you please try below dynamic SQL query?
DECLARE #oldTableName nvarchar(50)
DECLARE #newStagingTableName nvarchar(50)
SET #oldTableName='OldTableName'
SET #newStagingTableName ='NewTableName'
DECLARE #sqlquery nvarchar(100) = 'SELECT * INTO ' + #newStagingTableName + ' FROM ' + #oldTableName
exec(#sqlquery)
On the line
SELECT * INTO #newStagingTableNameFROM #oldTableName WHERE 1 = 0;
you do not have a space between #newStagingTableName and FROM
also check does the table NewTableName exist ? and if so you cannot just access it directly via a parameter - you would need to use dynamic SQL - perhaps this can help
Try with this
DECLARE #oldTableName NVARCHAR(50)
DECLARE #newStagingTableName NVARCHAR(50),
#sql NVARCHAR(100)=''
SET #oldTableName=''
SET #newStagingTableName ='';
SET #sql='select * INTO ' + #newStagingTableName
+ ' FROM ' + #oldTableName + ' WHERE 1 = 0;'
EXEC sp_executesql
#sql
this should work . . .
DECLARE #oldTableName nvarchar(50)
DECLARE #newStagingTableName nvarchar(50)
declare #sql nvarchar(max);
SET #oldTableName='oldTableName'
SET #newStagingTableName ='newStagingTableName ';
SET #sql='SELECT * INTO ' + #newStagingTableName + ' FROM ' + #oldTableName + ' WHERE 1 = 0;'
exec sp_executesql #sql
EDIT: Sorry I didnt see that other guys answered it
I want to run an ALTER TABLE that adds a default value constraint to a column.
I generate this statement dynamically from a .NET program.
How do I best format and quote the value when building my sql - now that ALTER TABLE statements does not support parameters (Gives the error 'Variables are not allowed in the ALTER TABLE statement').
Is there a utility for that in .NET? Or another solution?
You can do this in TSQL; for example, say you parameterize the command, passing in #DefaultValue, a varchar which may or may not be a valid TSQL literal. Because we are writing DDL, we will need to concatenate and exec, however we clearly don't want to blindly concatenate, as the value could be illegal. Fortunately, quotename does everything we need. By default, quotename outputs [qualified object names], but you can tell it to operate in literal escaping mode, for both single-quote and double-quote literals.
So our query that accepts #DefaultValue can build an SQL string:
declare #sql nvarchar(4000) = 'alter table ...';
-- ... blah
-- append the default value; note the result includes the outer quotes
#sql = #sql + quotename(#DefaultValue, '''');
-- ... blah
exec (#sql);
Full example:
--drop table FunkyDefaultExample
create table FunkyDefaultExample (id int not null)
declare #tableName varchar(20) = 'FunkyDefaultExample',
#colName varchar(20) = 'col name',
#defaultValue varchar(80) = 'test '' with quote';
-- the TSQL we want to generate to exec
/*
alter table [FunkyDefaultExample] add [col name] varchar(50) null
constraint [col name default] default 'test '' with quote';
*/
declare #sql nvarchar(4000) = 'alter table ' + quotename(#tablename)
+ ' add ' + quotename(#colName) + 'varchar(50) null constraint '
+ quotename(#colName + ' default') + ' default '
+ quotename(#defaultValue, '''');
exec (#sql);
-- tada!
string.Format("alter table YourTable add constraint DF_YourTable_Col1 default '{0}'",
inputValue.Replace("'", "''"));
We are working on a C# application, we've been using Linq to SQL or standard ADO (when performance needed) to work with SQL Server.
We have a table layed out like so:
Customer ID, Year/Month, Product Name, Quantity
Each customer has additional columns per product.
We need display this information in a data grid like so:
Customer, Year/Month, Product A Quantity, Product B Quantity, Product C Quantity, etc.
What query could give us these results? And how could it be dynamic no matter what products are added and removed? We will be using a ListView in WPF for displaying the data.
We would just store the information differently, but they can add/remove products all the time.
Will PIVOT work?
(PS - the product names are really in another table for normalization, I changed it a little for simplicity for you guys)
The sql pivot command can be used but it requires the columns to be hard-coded. You could either hard-code them, use dynamic sql to generate the columns, or only get the raw data from sql without a pivot and do the data massaging in c#.
You can use pivot with dynamic SQL. Following T-SQL code is taken from this article on sqlteam.com. I've tried to modify the sample for your needs. Also beware of dangers using dynamic SQL, it might lead to SQL Injection if a product name contains apostrophe.
Create a stored proc first;
CREATE PROCEDURE crosstab
#select varchar(8000),
#sumfunc varchar(100),
#pivot varchar(100),
#table varchar(100)
AS
DECLARE #sql varchar(8000), #delim varchar(1)
SET NOCOUNT ON
SET ANSI_WARNINGS OFF
EXEC ('SELECT ' + #pivot + ' AS pivot INTO ##pivot FROM ' + #table + ' WHERE 1=2')
EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + #pivot + ' FROM ' + #table + ' WHERE '
+ #pivot + ' Is Not Null')
SELECT #sql='', #sumfunc=stuff(#sumfunc, len(#sumfunc), 1, ' END)' )
SELECT #delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) )
WHEN 0 THEN '' ELSE '''' END
FROM tempdb.information_schema.columns
WHERE table_name='##pivot' AND column_name='pivot'
SELECT #sql=#sql + '''' + convert(varchar(100), pivot) + ''' = ' +
stuff(#sumfunc,charindex( '(', #sumfunc )+1, 0, ' CASE ' + #pivot + ' WHEN '
+ #delim + convert(varchar(100), pivot) + #delim + ' THEN ' ) + ', ' FROM ##pivot
DROP TABLE ##pivot
SELECT #sql=left(#sql, len(#sql)-1)
SELECT #select=stuff(#select, charindex(' FROM ', #select)+1, 0, ', ' + #sql + ' ')
EXEC (#select)
SET ANSI_WARNINGS ON
Then try the following (I haven't test it, you might need to add qty to select statement)
EXECUTE crosstab 'select ProductID,CustomerID, YearMonth from sales group by ProductId', 'sum(qty)','ProductId','sales'
If you want to try a method that doesn't involve dynamic SQL, you could go through C#.
This guy ran a test comparing the two: http://weblogs.sqlteam.com/jeffs/jeffs/archive/2005/05/12/5127.aspx