2015-10-01 70 views
1

問題插入SQL字符串值:我想「N/A」加入到我的@SQL選擇如何使用時,SET @sql

查詢:我可以添加「知道」值或做我需要聲明他們並根據tableName添加?

測試:我曾嘗試:

'+ 'N/A' +' 和 '+ 「N/A」 +'

注意:如果刪除了N/A線代碼工作。

錯誤:無效的列名稱'N/A'。

代碼:

USE [DB] 
GO 
/****** Object: StoredProcedure [dbo].[spExcelIntoTable] Script Date: 01/10/2015 13:27:05 ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 

ALTER PROCEDURE [dbo].[spExcelIntoTable] 
(
    @tableName   NVARCHAR(256)  
) 
AS 
BEGIN 

DECLARE @sql NVARCHAR(MAX) 

SET @sql = 'SELECT a.ID AS ID, 
a.UPRN,p.BuildingNo, 
p.Street,p.Postcode , 
a.ItemRef,a.SurveyDate , 
a.OverallRiskCategory , 
a.SurveyorsComments 

INTO TEMP_' + @tableName + ' 

FROM TblAsbestos 

AS a JOIN TblProperty 
As p on a.UPRN = p.UPRN 
WHERE a.OverallRiskCategory <> "N/A" 
ORDER BY a.OverallRiskCategory' 

EXEC (@sql) 

END 
GO 
+0

或有一列標識符一個臨時表,無論你做的範圍...... –

+0

你應該至少在QUOTENAME中包裝變量以幫助防止sql注入。 –

+0

QUOTENAME? @SeanLange我想避免注射! – indofraiser

回答

1

動態SQL代碼使用雙'

WHERE a.OverallRiskCategory <> ''N/A'' 
2

雙引號在SQL Server對象標識符,您需要使用兩個單引號使用字符串leteral。

目前SQL Server在處理「N/A」作爲列名"N/A"

SET @sql = 'SELECT a.ID AS ID, 
a.UPRN,p.BuildingNo, 
p.Street,p.Postcode , 
a.ItemRef,a.SurveyDate , 
a.OverallRiskCategory , 
a.SurveyorsComments 

INTO TEMP_' + @tableName + ' 

FROM TblAsbestos 

AS a JOIN TblProperty 
As p on a.UPRN = p.UPRN 
WHERE a.OverallRiskCategory <> ''N/A'' 
ORDER BY a.OverallRiskCategory'