Click here to Skip to main content
15,918,976 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to set DB Name as a generic variable in SQL and DB Name being repeated. I am inserting data from one database to another in SQL. I want to avoid repeating DB Name for each insert into select from queries. My sample queries are below.

What I have tried:

My query is as below:

abc -DB Name, dbo-schema name and Test, Test1 are the tables in the insert into select from Query blocks

SQL
INSERT INTO abc.dbo.Test
(
	   [IN_300_FileID]
      ,[RecordVer]
)
select from dbo.Test (in_300_id,record) 

INSERT INTO abc.dbo.Test1
(
	   [IN_300_FileID]
      ,[RecordVer]
)
select from dbo.Test1 (in_300_id,record)
Posted
Updated 2-Feb-22 2:56am
v3

You can't use a variable in place of a DB name in any query string - it's processed at a different level, and just won't work.

The only way to do that would be to write a string in SQL that evaluated the DB name into the string, and then use EXEC to execute the string.

But a much better idea to to handle it in your presentation language when you create the string in the first place - add some "template" characters (like "{DBNAME} for example) and just use the PL string Replace function.
 
Share this answer
 
You can achieved through Dynamic SQL Query. Below is the sample query, you can modify it according to your needs:
DECLARE @TSQL AS NVARCHAR(500)
DECLARE @databaseName AS NVARCHAR(20) = 'DBName'

SET @TSQL = N' INSERT INTO [' + @databaseName + '].dbo.Test([IN_300_FileID],[RecordVer]) '
SET @TSQL = @TSQL + N' SELECT FROM dbo.Test (in_300_id,record) '
SET @TSQL = @TSQL + N' INSERT INTO [' + @databaseName + '].dbo.Test1([IN_300_FileID],[RecordVer]) '	   
SET @TSQL = @TSQL + N' SELECT FROM dbo.Test1 (in_300_id,record) '
PRINT(@TSQL)

PRINT Result:
INSERT INTO [DBName].dbo.Test([IN_300_FileID],[RecordVer])
SELECT FROM dbo.Test (in_300_id,record)
INSERT INTO [DBName].dbo.Test1([IN_300_FileID],[RecordVer])
SELECT FROM dbo.Test1 (in_300_id,record)
Finally execute you build query with EXEC sp_executesql @TSQL command.
 
Share this answer
 
If you want to avoid repeating the three/four-part name, the simplest option would probably be to create synonyms for the tables you want to update:
Synonyms (Database Engine) - SQL Server | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900