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
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
We're looking to do an update in several SQL Server databases to change all NULL values in a certain table to be empty strings instead of NULL. We're potentially going to be doing this across hundreds of databases. The table name will always be the same, but the column names are variable based on how the front-end application is configured (don't judge... I didn't create this system).
Is there a way to do an update on all of these columns without knowing the column names ahead of time?
You can pass the name of the column in dynamic sql:
declare #sql nvarchar (1000);
set #sql = N'update table set ' + #column_name + '= ''''';
exec sp_executesql #sql;
You can look in the sys.columns table and join on the table name or object_id.
DECLARE #OBJ_ID INT
SELECT #OBJ_ID = OBJECT_ID
FROM SYS.tables
WHERE name = 'YOURTABLE'
SELECT * FROM SYS.columns
WHERE OBJECT_ID = #OBJ_ID
You could use the name field from the sys.columns query as a basis to perform the update on.
Assuming you want all columns of varchar/char types only (or change the type filter to whatever you need):
DECLARE #tableName varchar(10)
SET #tableName = 'yourtablenamehere'
DECLARE #sql VARCHAR(MAX)
SET #sql = ''
SELECT #sql = #sql + 'UPDATE ' + #tableName + ' SET ' + c.name + ' = '''' WHERE ' + c.name + ' IS NULL ;'
FROM sys.columns c
INNER JOIN sys.tables t ON c.object_id = t.object_id
INNER JOIN sys.types y ON c.system_type_id = y.system_type_id
WHERE t.name = #tableName AND y.name IN ('varchar', 'nvarchar', 'char', 'nchar')
EXEC (#sql)
This can be achieved with cursors. You first select the column names like #Darren mentioned, then you Set a Cursor with those values and loop:
Open oColumnsCursor
Fetch Next From oColumnscursor
Into #ColumnName
While ##FETCH_STATUS=0
Begin
Set #oQuery = 'Update [DB]..[Table] Set [' + #ColumnName + '] = ''NewValue'' Where [' + #ColumnName + '] = ''OldValue'''
Execute(#oQuery)
Fetch Next From oColumnscursor Into #ColumnName
Set #oCount = #oCount + 1
End
Close oColumnsCursor;
Deallocate oColumnsCursor;
This will work when you know the Table Name:
DECLARE #tableName varchar(10)
SET #tableName = 'Customers'
DECLARE #sql VARCHAR(MAX)
SET #sql = ''
SELECT #sql = #sql + 'UPDATE ' + #tableName + ' SET ' + c.name + ' = ISNULL('+ c.name +','''');'
FROM sys.columns c
INNER JOIN sys.tables t ON c.object_id = t.object_id
INNER JOIN sys.types y ON c.system_type_id = y.system_type_id
WHERE y.name IN ('varchar', 'nvarchar', 'char', 'nchar')
AND t.name = #tableName;
EXEC(#sql);
And this will iterate all Tables and all Columns in a Db:
DECLARE #sql VARCHAR(MAX)
SET #sql = ''
SELECT #sql = #sql + 'UPDATE ' + t.name + ' SET ' + c.name + ' = ISNULL('+ c.name +','''');'
FROM sys.columns c
INNER JOIN sys.tables t ON c.object_id = t.object_id
INNER JOIN sys.types y ON c.system_type_id = y.system_type_id
WHERE y.name IN ('varchar', 'nvarchar', 'char', 'nchar');
EXEC(#sql);
Below is the procedure.
ALTER PROCEDURE [dbo].[util_db_updateRow]
#colval_name NVARCHAR (30), -- column and values e.g. tax='5.50'
#idf_name NVARCHAR (300), -- column name
#idn_name NVARCHAR (300), -- column value
#tbl_name NVARCHAR (100) -- table name
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX)
-- construct SQL
SET #sql = 'UPDATE ' + #tbl_name + ' SET ' + #colval_name +
' WHERE ' + #idf_name + '=' + #idn_name;
-- execute the SQL
EXEC sp_executesql #sql
SET NOCOUNT OFF
RETURN
END
Below is the stored procedure where you can pass Schema Name, Table Name and list of column names separted by comma.It works only in Sql Server 2016 or higher.
CREATE OR ALTER PROCEDURE UpdateData
(#SchemaName NVARCHAR(Max),#TableName NVARCHAR(MAX),#ColumnNames NVARCHAR(MAX))
AS
BEGIN
DECLARE #DynamicSql NVARCHAR(MAX);
SET #DynamicSql = 'UPDATE ' +'[' +#SchemaName+'].' + '[' +#TableName+']' +' SET ' + STUFF((SELECT ', [' + C.name + '] = ' + '''NEW_VALUE'''
FROM sys.columns C
INNER JOIN sys.tables T ON T.object_id = C.object_id
INNER JOIN sys.schemas S ON T.schema_id = S.schema_id
WHERE
T.name = #TableName
AND S.Name = #SchemaName
AND [C].[name] in (SELECT VALUE FROM string_split(#ColumnNames,','))
FOR XML PATH('')), 1,1, '')
print #DynamicSql;
EXEC (#DynamicSql);
END
I have a database in which contain product details The product code, name etc are the columns, I have the product images in the system in a folder I need to add the images directly to the database according to the proper rows regarding the product code, The product code and images are sam, the product code is like 110-1,110-2 etc, and image names are 110-1jpg,110-2jpg etc I have a program but its not updating all the rows pls help
DECLARE #CODE varchar
DECLARE image_cursor CURSOR FOR
SELECT CODE FROM MyMast WHERE img IS NULL
OPEN image_cursor;
FETCH NEXT FROM image_cursor
INTO #CODE;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #sql VARCHAR(MAX)
DECLARE #imagePath VARCHAR(255)
SET #imagePath = 'D:\images\' + RTRIM(LTRIM(#CODE)) + '.jpg'
SET #sql = 'UPDATE Mymast'
SET #sql = #sql + 'SET img = (SELECT BulkColumn FROM OPENROWSET( BULK ''' + #imagePath + ''', Single_Blob) AS Picture), SET PictureFileName = ' + #imagepath
SET #sql = #sql + 'WHERE CODE = ''' + #CODE + ''';'
BEGIN TRY
EXECUTE sp_executesql #sql
END TRY
BEGIN CATCH
END CATCH
FETCH NEXT FROM image_cursor
INTO #CODE;
END
CLOSE image_cursor;
DEALLOCATE image_cursor;
SELECT CODE, img FROM MyMast WHERE img IS NOT NULL
DECLARE #CODE int
DECLARE image_cursor CURSOR FOR
SELECT CODE FROM MyMast WHERE img IS NULL
OPEN image_cursor;
FETCH NEXT FROM image_cursor
INTO #CODE;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #sql NVARCHAR(MAX)
DECLARE #imagePath NVARCHAR(255)
SET #imagePath = 'D:\images\'+ RTRIM(LTRIM('12')) + '.jpg'
SET #sql = 'UPDATE MyMast '
SET #sql = #sql + 'SET img = (SELECT BulkColumn FROM OPENROWSET( BULK ''' + #imagePath + ''', Single_Blob) AS img) '
SET #sql = #sql + 'WHERE CODE = ' + STR(#CODE)
BEGIN TRY
EXECUTE sp_executesql #sql
END TRY
BEGIN CATCH
END CATCH
FETCH NEXT FROM image_cursor
INTO #CODE;
END
CLOSE image_cursor;
DEALLOCATE image_cursor;
SELECT CODE, img FROM MyMast WHERE img IS NOT NULL
I have tried this code, but it shows error in convertion of nvarchar to float, code is in the format 110-1
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
declare #nopqty decimal(10,2)
declare #ntotamt decimal(10,2)
declare #npartno nvarchar(20)
SET #Orgcd =101
SET #npartno = "A 0001 150"
declare #qry nvarchar(4000)
SET #qry = 'SELECT #nopqty = oqty' + convert(varchar(3), #norgcd) +
', #ntotamt = ocost' + convert(varchar(3), #norgcd) +
' FROM stock WHERE part = #npartno'
exec sp_executesql #qry
Error
Must declare the scalar variable
Then I used
exec sp_executesql #qry, N'#nopqty decimal(10,2),#ntotamt decimal(10,2),#npartno nvarchar(20)',#nopqty=#nopqty,#ntotamt=#ntotamt,#npartno=#npartno
but when print #nopqty, #ntotamt it is null
How can I take out #nopqty, #ntotamt from these #qry?
I need these value for some calculation
Specify the parameter as output. For example:
declare #name varchar(10)
exec sp_executesql
N'select top 1 #name = name from sys.tables',
N'#name varchar(10) output',
#name = #name output
print #name